Raincleared commited on
Commit
d298f48
1 Parent(s): 3a99ae4

Upload folder using huggingface_hub

Browse files
config.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "SparseLLM/prosparse-llama-2-7b",
3
+ "architectures": [
4
+ "SparseLlamaForCausalLM"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_sparsellama.SparseLlamaConfig",
8
+ "AutoModel": "modeling_sparsellama.SparseLlamaForCausalLM",
9
+ "AutoModelForCausalLM": "modeling_sparsellama.SparseLlamaForCausalLM"
10
+ },
11
+ "bos_token_id": 1,
12
+ "eos_token_id": 2,
13
+ "hidden_act": "fatrelu",
14
+ "hidden_act_param": 0.01,
15
+ "hidden_size": 4096,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 11008,
18
+ "max_position_embeddings": 4096,
19
+ "model_type": "sparsellama",
20
+ "num_attention_heads": 32,
21
+ "num_hidden_layers": 32,
22
+ "num_key_value_heads": 32,
23
+ "pretraining_tp": 1,
24
+ "rms_norm_eps": 1e-05,
25
+ "rope_scaling": null,
26
+ "tie_word_embeddings": false,
27
+ "torch_dtype": "bfloat16",
28
+ "transformers_version": "4.31.0.dev0",
29
+ "use_cache": true,
30
+ "vocab_size": 32000,
31
+ "max_length": 4096
32
+ }
configuration_sparsellama.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+ LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
29
+
30
+
31
+ class SparseLlamaConfig(PretrainedConfig):
32
+ r"""
33
+ This is the configuration class to store the configuration of a [`LlamaModel`]. It is used to instantiate an LLaMA
34
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
35
+ defaults will yield a similar configuration to that of the LLaMA-7B.
36
+
37
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
38
+ documentation from [`PretrainedConfig`] for more information.
39
+
40
+
41
+ Args:
42
+ vocab_size (`int`, *optional*, defaults to 32000):
43
+ Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
44
+ `inputs_ids` passed when calling [`LlamaModel`]
45
+ hidden_size (`int`, *optional*, defaults to 4096):
46
+ Dimension of the hidden representations.
47
+ intermediate_size (`int`, *optional*, defaults to 11008):
48
+ Dimension of the MLP representations.
49
+ num_hidden_layers (`int`, *optional*, defaults to 32):
50
+ Number of hidden layers in the Transformer decoder.
51
+ num_attention_heads (`int`, *optional*, defaults to 32):
52
+ Number of attention heads for each attention layer in the Transformer decoder.
53
+ num_key_value_heads (`int`, *optional*):
54
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
55
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
56
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
57
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
58
+ by meanpooling all the original heads within that group. For more details checkout [this
59
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
60
+ `num_attention_heads`.
61
+ hidden_act (`str` or `function`, *optional*, defaults to `"fatrelu"`):
62
+ The non-linear activation function (function or string) in the decoder.
63
+ hidden_act_param (`float`, *optional*, defaults to 0.):
64
+ The bias for shiftrelu or threshold for fatrelu.
65
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
66
+ The maximum sequence length that this model might ever be used with. Llama 1 supports up to 2048 tokens,
67
+ Llama 2 up to 4096, CodeLlama up to 16384.
68
+ initializer_range (`float`, *optional*, defaults to 0.02):
69
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
70
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
71
+ The epsilon used by the rms normalization layers.
72
+ use_cache (`bool`, *optional*, defaults to `True`):
73
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
74
+ relevant if `config.is_decoder=True`.
75
+ pad_token_id (`int`, *optional*):
76
+ Padding token id.
77
+ bos_token_id (`int`, *optional*, defaults to 1):
78
+ Beginning of stream token id.
79
+ eos_token_id (`int`, *optional*, defaults to 2):
80
+ End of stream token id.
81
+ pretraining_tp (`int`, *optional*, defaults to 1):
82
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
83
+ document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
84
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
85
+ issue](https://github.com/pytorch/pytorch/issues/76232).
86
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
87
+ Whether to tie weight embeddings
88
+ rope_theta (`float`, *optional*, defaults to 10000.0):
89
+ The base period of the RoPE embeddings.
90
+ rope_scaling (`Dict`, *optional*):
91
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
92
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
93
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
94
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
95
+ these scaling strategies behave:
96
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
97
+ experimental feature, subject to breaking API changes in future versions.
98
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
99
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
100
+
101
+
102
+ ```python
103
+ >>> from transformers import LlamaModel, LlamaConfig
104
+
105
+ >>> # Initializing a LLaMA llama-7b style configuration
106
+ >>> configuration = LlamaConfig()
107
+
108
+ >>> # Initializing a model from the llama-7b style configuration
109
+ >>> model = LlamaModel(configuration)
110
+
111
+ >>> # Accessing the model configuration
112
+ >>> configuration = model.config
113
+ ```"""
114
+ model_type = "sparsellama"
115
+ keys_to_ignore_at_inference = ["past_key_values"]
116
+
117
+ def __init__(
118
+ self,
119
+ vocab_size=32000,
120
+ hidden_size=4096,
121
+ intermediate_size=11008,
122
+ num_hidden_layers=32,
123
+ num_attention_heads=32,
124
+ num_key_value_heads=None,
125
+ hidden_act="fatrelu",
126
+ hidden_act_param=0.,
127
+ max_position_embeddings=2048,
128
+ initializer_range=0.02,
129
+ rms_norm_eps=1e-6,
130
+ use_cache=True,
131
+ pad_token_id=None,
132
+ bos_token_id=1,
133
+ eos_token_id=2,
134
+ pretraining_tp=1,
135
+ tie_word_embeddings=False,
136
+ rope_theta=10000.0,
137
+ rope_scaling=None,
138
+ attention_bias=False,
139
+ **kwargs,
140
+ ):
141
+ self.vocab_size = vocab_size
142
+ self.max_position_embeddings = max_position_embeddings
143
+ self.hidden_size = hidden_size
144
+ self.intermediate_size = intermediate_size
145
+ self.num_hidden_layers = num_hidden_layers
146
+ self.num_attention_heads = num_attention_heads
147
+
148
+ # for backward compatibility
149
+ if num_key_value_heads is None:
150
+ num_key_value_heads = num_attention_heads
151
+
152
+ self.num_key_value_heads = num_key_value_heads
153
+ self.hidden_act = hidden_act
154
+ self.hidden_act_param = hidden_act_param
155
+ self.initializer_range = initializer_range
156
+ self.rms_norm_eps = rms_norm_eps
157
+ self.pretraining_tp = pretraining_tp
158
+ self.use_cache = use_cache
159
+ self.rope_theta = rope_theta
160
+ self.rope_scaling = rope_scaling
161
+ self._rope_scaling_validation()
162
+ self.attention_bias = attention_bias
163
+
164
+ super().__init__(
165
+ pad_token_id=pad_token_id,
166
+ bos_token_id=bos_token_id,
167
+ eos_token_id=eos_token_id,
168
+ tie_word_embeddings=tie_word_embeddings,
169
+ **kwargs,
170
+ )
171
+
172
+ def _rope_scaling_validation(self):
173
+ """
174
+ Validate the `rope_scaling` configuration.
175
+ """
176
+ if self.rope_scaling is None:
177
+ return
178
+
179
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
180
+ raise ValueError(
181
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
182
+ f"got {self.rope_scaling}"
183
+ )
184
+ rope_scaling_type = self.rope_scaling.get("type", None)
185
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
186
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
187
+ raise ValueError(
188
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
189
+ )
190
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
191
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
generation_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 1,
3
+ "do_sample": true,
4
+ "eos_token_id": 2,
5
+ "pad_token_id": 0,
6
+ "temperature": 0.6,
7
+ "max_length": 4096,
8
+ "top_p": 0.9,
9
+ "transformers_version": "4.31.0.dev0"
10
+ }
model-00001-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4a389991e45d11bcee0e53d70e3f0a35716c5cae3ce3e7949cb575c1d27db45e
3
+ size 4840396416
model-00002-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:30ea0875f7ed94ec3d950a936516edcdc19e558ed14216320e53d054c75c27ee
3
+ size 4857206856
model-00003-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c800d8a223c4fb4ce0fa9d43c935b7657bf5da0e93cd752c211924551b21f6b8
3
+ size 4857206904
model-00004-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:abe69591a3c5dbfbdb8e89d8d1a3d24b46c467cf619dc2431ae499b2b74e4219
3
+ size 4857206904
model-00005-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:24342b37ca4e02d939ea16d5346a502eeb4331919bc57288ece53e0276552ab8
3
+ size 4857206904
model-00006-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b26618d0e5d42c0dc683f9e89651e86ef229cf8e018b6616715780a8a1faede3
3
+ size 2684472112
model.safetensors.index.json ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 26953662464
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-00006-of-00006.safetensors",
7
+ "model.embed_tokens.weight": "model-00001-of-00006.safetensors",
8
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00006.safetensors",
9
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
10
+ "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00006.safetensors",
11
+ "model.layers.0.mlp.up_proj.weight": "model-00001-of-00006.safetensors",
12
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00006.safetensors",
13
+ "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00006.safetensors",
14
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
15
+ "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00006.safetensors",
16
+ "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00006.safetensors",
17
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00006.safetensors",
18
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
19
+ "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00006.safetensors",
20
+ "model.layers.1.mlp.up_proj.weight": "model-00001-of-00006.safetensors",
21
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00006.safetensors",
22
+ "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00006.safetensors",
23
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
24
+ "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00006.safetensors",
25
+ "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00006.safetensors",
26
+ "model.layers.10.input_layernorm.weight": "model-00002-of-00006.safetensors",
27
+ "model.layers.10.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
28
+ "model.layers.10.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
29
+ "model.layers.10.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
30
+ "model.layers.10.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
31
+ "model.layers.10.self_attn.k_proj.weight": "model-00002-of-00006.safetensors",
32
+ "model.layers.10.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
33
+ "model.layers.10.self_attn.q_proj.weight": "model-00002-of-00006.safetensors",
34
+ "model.layers.10.self_attn.v_proj.weight": "model-00002-of-00006.safetensors",
35
+ "model.layers.11.input_layernorm.weight": "model-00003-of-00006.safetensors",
36
+ "model.layers.11.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
37
+ "model.layers.11.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
38
+ "model.layers.11.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
39
+ "model.layers.11.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
40
+ "model.layers.11.self_attn.k_proj.weight": "model-00002-of-00006.safetensors",
41
+ "model.layers.11.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
42
+ "model.layers.11.self_attn.q_proj.weight": "model-00002-of-00006.safetensors",
43
+ "model.layers.11.self_attn.v_proj.weight": "model-00002-of-00006.safetensors",
44
+ "model.layers.12.input_layernorm.weight": "model-00003-of-00006.safetensors",
45
+ "model.layers.12.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
46
+ "model.layers.12.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
47
+ "model.layers.12.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
48
+ "model.layers.12.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
49
+ "model.layers.12.self_attn.k_proj.weight": "model-00003-of-00006.safetensors",
50
+ "model.layers.12.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
51
+ "model.layers.12.self_attn.q_proj.weight": "model-00003-of-00006.safetensors",
52
+ "model.layers.12.self_attn.v_proj.weight": "model-00003-of-00006.safetensors",
53
+ "model.layers.13.input_layernorm.weight": "model-00003-of-00006.safetensors",
54
+ "model.layers.13.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
55
+ "model.layers.13.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
56
+ "model.layers.13.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
57
+ "model.layers.13.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
58
+ "model.layers.13.self_attn.k_proj.weight": "model-00003-of-00006.safetensors",
59
+ "model.layers.13.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
60
+ "model.layers.13.self_attn.q_proj.weight": "model-00003-of-00006.safetensors",
61
+ "model.layers.13.self_attn.v_proj.weight": "model-00003-of-00006.safetensors",
62
+ "model.layers.14.input_layernorm.weight": "model-00003-of-00006.safetensors",
63
+ "model.layers.14.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
64
+ "model.layers.14.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
65
+ "model.layers.14.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
66
+ "model.layers.14.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
67
+ "model.layers.14.self_attn.k_proj.weight": "model-00003-of-00006.safetensors",
68
+ "model.layers.14.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
69
+ "model.layers.14.self_attn.q_proj.weight": "model-00003-of-00006.safetensors",
70
+ "model.layers.14.self_attn.v_proj.weight": "model-00003-of-00006.safetensors",
71
+ "model.layers.15.input_layernorm.weight": "model-00003-of-00006.safetensors",
72
+ "model.layers.15.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
73
+ "model.layers.15.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
74
+ "model.layers.15.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
75
+ "model.layers.15.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
76
+ "model.layers.15.self_attn.k_proj.weight": "model-00003-of-00006.safetensors",
77
+ "model.layers.15.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
78
+ "model.layers.15.self_attn.q_proj.weight": "model-00003-of-00006.safetensors",
79
+ "model.layers.15.self_attn.v_proj.weight": "model-00003-of-00006.safetensors",
80
+ "model.layers.16.input_layernorm.weight": "model-00003-of-00006.safetensors",
81
+ "model.layers.16.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
82
+ "model.layers.16.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
83
+ "model.layers.16.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
84
+ "model.layers.16.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
85
+ "model.layers.16.self_attn.k_proj.weight": "model-00003-of-00006.safetensors",
86
+ "model.layers.16.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
87
+ "model.layers.16.self_attn.q_proj.weight": "model-00003-of-00006.safetensors",
88
+ "model.layers.16.self_attn.v_proj.weight": "model-00003-of-00006.safetensors",
89
+ "model.layers.17.input_layernorm.weight": "model-00004-of-00006.safetensors",
90
+ "model.layers.17.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
91
+ "model.layers.17.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
92
+ "model.layers.17.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
93
+ "model.layers.17.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
94
+ "model.layers.17.self_attn.k_proj.weight": "model-00003-of-00006.safetensors",
95
+ "model.layers.17.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
96
+ "model.layers.17.self_attn.q_proj.weight": "model-00003-of-00006.safetensors",
97
+ "model.layers.17.self_attn.v_proj.weight": "model-00003-of-00006.safetensors",
98
+ "model.layers.18.input_layernorm.weight": "model-00004-of-00006.safetensors",
99
+ "model.layers.18.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
100
+ "model.layers.18.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
101
+ "model.layers.18.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
102
+ "model.layers.18.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
103
+ "model.layers.18.self_attn.k_proj.weight": "model-00004-of-00006.safetensors",
104
+ "model.layers.18.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
105
+ "model.layers.18.self_attn.q_proj.weight": "model-00004-of-00006.safetensors",
106
+ "model.layers.18.self_attn.v_proj.weight": "model-00004-of-00006.safetensors",
107
+ "model.layers.19.input_layernorm.weight": "model-00004-of-00006.safetensors",
108
+ "model.layers.19.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
109
+ "model.layers.19.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
110
+ "model.layers.19.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
111
+ "model.layers.19.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
112
+ "model.layers.19.self_attn.k_proj.weight": "model-00004-of-00006.safetensors",
113
+ "model.layers.19.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
114
+ "model.layers.19.self_attn.q_proj.weight": "model-00004-of-00006.safetensors",
115
+ "model.layers.19.self_attn.v_proj.weight": "model-00004-of-00006.safetensors",
116
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00006.safetensors",
117
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
118
+ "model.layers.2.mlp.gate_proj.weight": "model-00001-of-00006.safetensors",
119
+ "model.layers.2.mlp.up_proj.weight": "model-00001-of-00006.safetensors",
120
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00006.safetensors",
121
+ "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00006.safetensors",
122
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
123
+ "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00006.safetensors",
124
+ "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00006.safetensors",
125
+ "model.layers.20.input_layernorm.weight": "model-00004-of-00006.safetensors",
126
+ "model.layers.20.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
127
+ "model.layers.20.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
128
+ "model.layers.20.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
129
+ "model.layers.20.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
130
+ "model.layers.20.self_attn.k_proj.weight": "model-00004-of-00006.safetensors",
131
+ "model.layers.20.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
132
+ "model.layers.20.self_attn.q_proj.weight": "model-00004-of-00006.safetensors",
133
+ "model.layers.20.self_attn.v_proj.weight": "model-00004-of-00006.safetensors",
134
+ "model.layers.21.input_layernorm.weight": "model-00004-of-00006.safetensors",
135
+ "model.layers.21.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
136
+ "model.layers.21.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
137
+ "model.layers.21.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
138
+ "model.layers.21.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
139
+ "model.layers.21.self_attn.k_proj.weight": "model-00004-of-00006.safetensors",
140
+ "model.layers.21.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
141
+ "model.layers.21.self_attn.q_proj.weight": "model-00004-of-00006.safetensors",
142
+ "model.layers.21.self_attn.v_proj.weight": "model-00004-of-00006.safetensors",
143
+ "model.layers.22.input_layernorm.weight": "model-00004-of-00006.safetensors",
144
+ "model.layers.22.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
145
+ "model.layers.22.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
146
+ "model.layers.22.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
147
+ "model.layers.22.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
148
+ "model.layers.22.self_attn.k_proj.weight": "model-00004-of-00006.safetensors",
149
+ "model.layers.22.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
150
+ "model.layers.22.self_attn.q_proj.weight": "model-00004-of-00006.safetensors",
151
+ "model.layers.22.self_attn.v_proj.weight": "model-00004-of-00006.safetensors",
152
+ "model.layers.23.input_layernorm.weight": "model-00005-of-00006.safetensors",
153
+ "model.layers.23.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
154
+ "model.layers.23.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
155
+ "model.layers.23.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
156
+ "model.layers.23.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
157
+ "model.layers.23.self_attn.k_proj.weight": "model-00004-of-00006.safetensors",
158
+ "model.layers.23.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
159
+ "model.layers.23.self_attn.q_proj.weight": "model-00004-of-00006.safetensors",
160
+ "model.layers.23.self_attn.v_proj.weight": "model-00004-of-00006.safetensors",
161
+ "model.layers.24.input_layernorm.weight": "model-00005-of-00006.safetensors",
162
+ "model.layers.24.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
163
+ "model.layers.24.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
164
+ "model.layers.24.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
165
+ "model.layers.24.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
166
+ "model.layers.24.self_attn.k_proj.weight": "model-00005-of-00006.safetensors",
167
+ "model.layers.24.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
168
+ "model.layers.24.self_attn.q_proj.weight": "model-00005-of-00006.safetensors",
169
+ "model.layers.24.self_attn.v_proj.weight": "model-00005-of-00006.safetensors",
170
+ "model.layers.25.input_layernorm.weight": "model-00005-of-00006.safetensors",
171
+ "model.layers.25.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
172
+ "model.layers.25.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
173
+ "model.layers.25.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
174
+ "model.layers.25.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
175
+ "model.layers.25.self_attn.k_proj.weight": "model-00005-of-00006.safetensors",
176
+ "model.layers.25.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
177
+ "model.layers.25.self_attn.q_proj.weight": "model-00005-of-00006.safetensors",
178
+ "model.layers.25.self_attn.v_proj.weight": "model-00005-of-00006.safetensors",
179
+ "model.layers.26.input_layernorm.weight": "model-00005-of-00006.safetensors",
180
+ "model.layers.26.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
181
+ "model.layers.26.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
182
+ "model.layers.26.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
183
+ "model.layers.26.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
184
+ "model.layers.26.self_attn.k_proj.weight": "model-00005-of-00006.safetensors",
185
+ "model.layers.26.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
186
+ "model.layers.26.self_attn.q_proj.weight": "model-00005-of-00006.safetensors",
187
+ "model.layers.26.self_attn.v_proj.weight": "model-00005-of-00006.safetensors",
188
+ "model.layers.27.input_layernorm.weight": "model-00005-of-00006.safetensors",
189
+ "model.layers.27.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
190
+ "model.layers.27.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
191
+ "model.layers.27.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
192
+ "model.layers.27.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
193
+ "model.layers.27.self_attn.k_proj.weight": "model-00005-of-00006.safetensors",
194
+ "model.layers.27.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
195
+ "model.layers.27.self_attn.q_proj.weight": "model-00005-of-00006.safetensors",
196
+ "model.layers.27.self_attn.v_proj.weight": "model-00005-of-00006.safetensors",
197
+ "model.layers.28.input_layernorm.weight": "model-00005-of-00006.safetensors",
198
+ "model.layers.28.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
199
+ "model.layers.28.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
200
+ "model.layers.28.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
201
+ "model.layers.28.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
202
+ "model.layers.28.self_attn.k_proj.weight": "model-00005-of-00006.safetensors",
203
+ "model.layers.28.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
204
+ "model.layers.28.self_attn.q_proj.weight": "model-00005-of-00006.safetensors",
205
+ "model.layers.28.self_attn.v_proj.weight": "model-00005-of-00006.safetensors",
206
+ "model.layers.29.input_layernorm.weight": "model-00006-of-00006.safetensors",
207
+ "model.layers.29.mlp.down_proj.weight": "model-00006-of-00006.safetensors",
208
+ "model.layers.29.mlp.gate_proj.weight": "model-00006-of-00006.safetensors",
209
+ "model.layers.29.mlp.up_proj.weight": "model-00006-of-00006.safetensors",
210
+ "model.layers.29.post_attention_layernorm.weight": "model-00006-of-00006.safetensors",
211
+ "model.layers.29.self_attn.k_proj.weight": "model-00005-of-00006.safetensors",
212
+ "model.layers.29.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
213
+ "model.layers.29.self_attn.q_proj.weight": "model-00005-of-00006.safetensors",
214
+ "model.layers.29.self_attn.v_proj.weight": "model-00005-of-00006.safetensors",
215
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00006.safetensors",
216
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
217
+ "model.layers.3.mlp.gate_proj.weight": "model-00001-of-00006.safetensors",
218
+ "model.layers.3.mlp.up_proj.weight": "model-00001-of-00006.safetensors",
219
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00006.safetensors",
220
+ "model.layers.3.self_attn.k_proj.weight": "model-00001-of-00006.safetensors",
221
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
222
+ "model.layers.3.self_attn.q_proj.weight": "model-00001-of-00006.safetensors",
223
+ "model.layers.3.self_attn.v_proj.weight": "model-00001-of-00006.safetensors",
224
+ "model.layers.30.input_layernorm.weight": "model-00006-of-00006.safetensors",
225
+ "model.layers.30.mlp.down_proj.weight": "model-00006-of-00006.safetensors",
226
+ "model.layers.30.mlp.gate_proj.weight": "model-00006-of-00006.safetensors",
227
+ "model.layers.30.mlp.up_proj.weight": "model-00006-of-00006.safetensors",
228
+ "model.layers.30.post_attention_layernorm.weight": "model-00006-of-00006.safetensors",
229
+ "model.layers.30.self_attn.k_proj.weight": "model-00006-of-00006.safetensors",
230
+ "model.layers.30.self_attn.o_proj.weight": "model-00006-of-00006.safetensors",
231
+ "model.layers.30.self_attn.q_proj.weight": "model-00006-of-00006.safetensors",
232
+ "model.layers.30.self_attn.v_proj.weight": "model-00006-of-00006.safetensors",
233
+ "model.layers.31.input_layernorm.weight": "model-00006-of-00006.safetensors",
234
+ "model.layers.31.mlp.down_proj.weight": "model-00006-of-00006.safetensors",
235
+ "model.layers.31.mlp.gate_proj.weight": "model-00006-of-00006.safetensors",
236
+ "model.layers.31.mlp.up_proj.weight": "model-00006-of-00006.safetensors",
237
+ "model.layers.31.post_attention_layernorm.weight": "model-00006-of-00006.safetensors",
238
+ "model.layers.31.self_attn.k_proj.weight": "model-00006-of-00006.safetensors",
239
+ "model.layers.31.self_attn.o_proj.weight": "model-00006-of-00006.safetensors",
240
+ "model.layers.31.self_attn.q_proj.weight": "model-00006-of-00006.safetensors",
241
+ "model.layers.31.self_attn.v_proj.weight": "model-00006-of-00006.safetensors",
242
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00006.safetensors",
243
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
244
+ "model.layers.4.mlp.gate_proj.weight": "model-00001-of-00006.safetensors",
245
+ "model.layers.4.mlp.up_proj.weight": "model-00001-of-00006.safetensors",
246
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00006.safetensors",
247
+ "model.layers.4.self_attn.k_proj.weight": "model-00001-of-00006.safetensors",
248
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
249
+ "model.layers.4.self_attn.q_proj.weight": "model-00001-of-00006.safetensors",
250
+ "model.layers.4.self_attn.v_proj.weight": "model-00001-of-00006.safetensors",
251
+ "model.layers.5.input_layernorm.weight": "model-00002-of-00006.safetensors",
252
+ "model.layers.5.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
253
+ "model.layers.5.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
254
+ "model.layers.5.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
255
+ "model.layers.5.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
256
+ "model.layers.5.self_attn.k_proj.weight": "model-00001-of-00006.safetensors",
257
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
258
+ "model.layers.5.self_attn.q_proj.weight": "model-00001-of-00006.safetensors",
259
+ "model.layers.5.self_attn.v_proj.weight": "model-00001-of-00006.safetensors",
260
+ "model.layers.6.input_layernorm.weight": "model-00002-of-00006.safetensors",
261
+ "model.layers.6.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
262
+ "model.layers.6.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
263
+ "model.layers.6.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
264
+ "model.layers.6.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
265
+ "model.layers.6.self_attn.k_proj.weight": "model-00002-of-00006.safetensors",
266
+ "model.layers.6.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
267
+ "model.layers.6.self_attn.q_proj.weight": "model-00002-of-00006.safetensors",
268
+ "model.layers.6.self_attn.v_proj.weight": "model-00002-of-00006.safetensors",
269
+ "model.layers.7.input_layernorm.weight": "model-00002-of-00006.safetensors",
270
+ "model.layers.7.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
271
+ "model.layers.7.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
272
+ "model.layers.7.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
273
+ "model.layers.7.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
274
+ "model.layers.7.self_attn.k_proj.weight": "model-00002-of-00006.safetensors",
275
+ "model.layers.7.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
276
+ "model.layers.7.self_attn.q_proj.weight": "model-00002-of-00006.safetensors",
277
+ "model.layers.7.self_attn.v_proj.weight": "model-00002-of-00006.safetensors",
278
+ "model.layers.8.input_layernorm.weight": "model-00002-of-00006.safetensors",
279
+ "model.layers.8.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
280
+ "model.layers.8.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
281
+ "model.layers.8.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
282
+ "model.layers.8.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
283
+ "model.layers.8.self_attn.k_proj.weight": "model-00002-of-00006.safetensors",
284
+ "model.layers.8.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
285
+ "model.layers.8.self_attn.q_proj.weight": "model-00002-of-00006.safetensors",
286
+ "model.layers.8.self_attn.v_proj.weight": "model-00002-of-00006.safetensors",
287
+ "model.layers.9.input_layernorm.weight": "model-00002-of-00006.safetensors",
288
+ "model.layers.9.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
289
+ "model.layers.9.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
290
+ "model.layers.9.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
291
+ "model.layers.9.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
292
+ "model.layers.9.self_attn.k_proj.weight": "model-00002-of-00006.safetensors",
293
+ "model.layers.9.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
294
+ "model.layers.9.self_attn.q_proj.weight": "model-00002-of-00006.safetensors",
295
+ "model.layers.9.self_attn.v_proj.weight": "model-00002-of-00006.safetensors",
296
+ "model.norm.weight": "model-00006-of-00006.safetensors"
297
+ }
298
+ }
modeling_sparsellama.py ADDED
@@ -0,0 +1,1262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """ PyTorch LLaMA model."""
21
+ import math
22
+ import warnings
23
+ from typing import List, Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.nn.functional as F
27
+ import torch.utils.checkpoint
28
+ from torch import nn
29
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
30
+
31
+ from transformers.activations import ACT2FN
32
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter, _prepare_4d_causal_attention_mask
33
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
34
+ from transformers.modeling_utils import PreTrainedModel
35
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
36
+ from transformers.utils import (
37
+ add_start_docstrings,
38
+ add_start_docstrings_to_model_forward,
39
+ is_flash_attn_2_available,
40
+ logging,
41
+ replace_return_docstrings,
42
+ )
43
+ from transformers.utils.import_utils import is_torch_fx_available
44
+ from .configuration_sparsellama import SparseLlamaConfig
45
+
46
+
47
+ if is_flash_attn_2_available():
48
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
49
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
50
+
51
+
52
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
53
+ # It means that the function will not be traced through and simply appear as a node in the graph.
54
+ if is_torch_fx_available():
55
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
56
+
57
+
58
+ logger = logging.get_logger(__name__)
59
+
60
+ _CONFIG_FOR_DOC = "LlamaConfig"
61
+
62
+
63
+ def _get_unpad_data(attention_mask):
64
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
65
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
66
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
67
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
68
+ return (
69
+ indices,
70
+ cu_seqlens,
71
+ max_seqlen_in_batch,
72
+ )
73
+
74
+
75
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
76
+ warnings.warn(
77
+ "Calling `transformers.models.llama.modeling_llama._prepare_4d_attention_mask` is deprecated and will be removed in v4.37. Use `transformers.modeling_attn_mask_utils.AttentionMaskConverter._prepare_4d_attention_mask"
78
+ )
79
+ return AttentionMaskConverter._prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
80
+
81
+
82
+ def _make_causal_mask(
83
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
84
+ ):
85
+ warnings.warn(
86
+ "Calling `transformers.models.llama.modeling_llama._make_causal_mask` is deprecated and will be removed in v4.37. Use `transformers.models.llama.modeling_llama.AttentionMaskConverter._make_causal_mask"
87
+ )
88
+ return AttentionMaskConverter._make_causal_mask(
89
+ input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length
90
+ )
91
+
92
+
93
+ class LlamaRMSNorm(nn.Module):
94
+ def __init__(self, hidden_size, eps=1e-6):
95
+ """
96
+ LlamaRMSNorm is equivalent to T5LayerNorm
97
+ """
98
+ super().__init__()
99
+ self.weight = nn.Parameter(torch.ones(hidden_size))
100
+ self.variance_epsilon = eps
101
+
102
+ def forward(self, hidden_states):
103
+ input_dtype = hidden_states.dtype
104
+ hidden_states = hidden_states.to(torch.float32)
105
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
106
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
107
+ return self.weight * hidden_states.to(input_dtype)
108
+
109
+
110
+ ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm)
111
+
112
+
113
+ class LlamaRotaryEmbedding(nn.Module):
114
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
115
+ super().__init__()
116
+
117
+ self.dim = dim
118
+ self.max_position_embeddings = max_position_embeddings
119
+ self.base = base
120
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
121
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
122
+
123
+ # Build here to make `torch.jit.trace` work.
124
+ self._set_cos_sin_cache(
125
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
126
+ )
127
+
128
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
129
+ self.max_seq_len_cached = seq_len
130
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
131
+
132
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
133
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
134
+ emb = torch.cat((freqs, freqs), dim=-1)
135
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
136
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
137
+
138
+ def forward(self, x, seq_len=None):
139
+ # x: [bs, num_attention_heads, seq_len, head_size]
140
+ if seq_len > self.max_seq_len_cached:
141
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
142
+
143
+ return (
144
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
145
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
146
+ )
147
+
148
+
149
+ class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
150
+ """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
151
+
152
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
153
+ self.scaling_factor = scaling_factor
154
+ super().__init__(dim, max_position_embeddings, base, device)
155
+
156
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
157
+ self.max_seq_len_cached = seq_len
158
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
159
+ t = t / self.scaling_factor
160
+
161
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
162
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
163
+ emb = torch.cat((freqs, freqs), dim=-1)
164
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
165
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
166
+
167
+
168
+ class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
169
+ """LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
170
+
171
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
172
+ self.scaling_factor = scaling_factor
173
+ super().__init__(dim, max_position_embeddings, base, device)
174
+
175
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
176
+ self.max_seq_len_cached = seq_len
177
+
178
+ if seq_len > self.max_position_embeddings:
179
+ base = self.base * (
180
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
181
+ ) ** (self.dim / (self.dim - 2))
182
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
183
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
184
+
185
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
186
+
187
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
188
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
189
+ emb = torch.cat((freqs, freqs), dim=-1)
190
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
191
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
192
+
193
+
194
+ def rotate_half(x):
195
+ """Rotates half the hidden dims of the input."""
196
+ x1 = x[..., : x.shape[-1] // 2]
197
+ x2 = x[..., x.shape[-1] // 2 :]
198
+ return torch.cat((-x2, x1), dim=-1)
199
+
200
+
201
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
202
+ """Applies Rotary Position Embedding to the query and key tensors.
203
+
204
+ Args:
205
+ q (`torch.Tensor`): The query tensor.
206
+ k (`torch.Tensor`): The key tensor.
207
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
208
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
209
+ position_ids (`torch.Tensor`):
210
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
211
+ used to pass offsetted position ids when working with a KV-cache.
212
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
213
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
214
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
215
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
216
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
217
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
218
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
219
+ Returns:
220
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
221
+ """
222
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
223
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
224
+ q_embed = (q * cos) + (rotate_half(q) * sin)
225
+ k_embed = (k * cos) + (rotate_half(k) * sin)
226
+ return q_embed, k_embed
227
+
228
+
229
+ class SparseLlamaMLP(nn.Module):
230
+ def __init__(self, config: SparseLlamaConfig):
231
+ super().__init__()
232
+ self.config = config
233
+ self.hidden_size = config.hidden_size
234
+ self.intermediate_size = config.intermediate_size
235
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
236
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
237
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
238
+ if config.hidden_act in ACT2FN:
239
+ self.act_fn = ACT2FN[config.hidden_act]
240
+ elif config.hidden_act == "shiftrelu":
241
+ def shifted_relu(x):
242
+ return torch.nn.functional.relu(x - config.hidden_act_param)
243
+ self.act_fn = shifted_relu
244
+ elif config.hidden_act == "fatrelu":
245
+ def fat_relu(x):
246
+ new_x = torch.zeros_like(x)
247
+ mask = torch.ge(x, config.hidden_act_param)
248
+ new_x[mask] = x[mask]
249
+ return new_x
250
+ self.act_fn = fat_relu
251
+ else:
252
+ raise NotImplementedError(f"Unsupported activation function: {config.hidden_act}")
253
+
254
+ def forward(self, x):
255
+ if self.config.pretraining_tp > 1:
256
+ slice = self.intermediate_size // self.config.pretraining_tp
257
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
258
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
259
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
260
+
261
+ gate_proj = torch.cat(
262
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
263
+ )
264
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
265
+
266
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
267
+ down_proj = [
268
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
269
+ ]
270
+ down_proj = sum(down_proj)
271
+ else:
272
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
273
+
274
+ return down_proj
275
+
276
+
277
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
278
+ """
279
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
280
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
281
+ """
282
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
283
+ if n_rep == 1:
284
+ return hidden_states
285
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
286
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
287
+
288
+
289
+ class LlamaAttention(nn.Module):
290
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
291
+
292
+ def __init__(self, config: SparseLlamaConfig):
293
+ super().__init__()
294
+ self.config = config
295
+ self.hidden_size = config.hidden_size
296
+ self.num_heads = config.num_attention_heads
297
+ self.head_dim = self.hidden_size // self.num_heads
298
+ self.num_key_value_heads = config.num_key_value_heads
299
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
300
+ self.max_position_embeddings = config.max_position_embeddings
301
+ self.rope_theta = config.rope_theta
302
+ self.is_causal = True
303
+
304
+ if (self.head_dim * self.num_heads) != self.hidden_size:
305
+ raise ValueError(
306
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
307
+ f" and `num_heads`: {self.num_heads})."
308
+ )
309
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
310
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
311
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
312
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
313
+ self._init_rope()
314
+
315
+ def _init_rope(self):
316
+ if self.config.rope_scaling is None:
317
+ self.rotary_emb = LlamaRotaryEmbedding(
318
+ self.head_dim,
319
+ max_position_embeddings=self.max_position_embeddings,
320
+ base=self.rope_theta,
321
+ )
322
+ else:
323
+ scaling_type = self.config.rope_scaling["type"]
324
+ scaling_factor = self.config.rope_scaling["factor"]
325
+ if scaling_type == "linear":
326
+ self.rotary_emb = LlamaLinearScalingRotaryEmbedding(
327
+ self.head_dim,
328
+ max_position_embeddings=self.max_position_embeddings,
329
+ scaling_factor=scaling_factor,
330
+ base=self.rope_theta,
331
+ )
332
+ elif scaling_type == "dynamic":
333
+ self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding(
334
+ self.head_dim,
335
+ max_position_embeddings=self.max_position_embeddings,
336
+ scaling_factor=scaling_factor,
337
+ base=self.rope_theta,
338
+ )
339
+ else:
340
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
341
+
342
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
343
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
344
+
345
+ def forward(
346
+ self,
347
+ hidden_states: torch.Tensor,
348
+ attention_mask: Optional[torch.Tensor] = None,
349
+ position_ids: Optional[torch.LongTensor] = None,
350
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
351
+ output_attentions: bool = False,
352
+ use_cache: bool = False,
353
+ **kwargs,
354
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
355
+ if "padding_mask" in kwargs:
356
+ warnings.warn(
357
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
358
+ )
359
+
360
+ bsz, q_len, _ = hidden_states.size()
361
+
362
+ if self.config.pretraining_tp > 1:
363
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
364
+ query_slices = self.q_proj.weight.split(
365
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
366
+ )
367
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
368
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
369
+
370
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
371
+ query_states = torch.cat(query_states, dim=-1)
372
+
373
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
374
+ key_states = torch.cat(key_states, dim=-1)
375
+
376
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
377
+ value_states = torch.cat(value_states, dim=-1)
378
+
379
+ else:
380
+ query_states = self.q_proj(hidden_states)
381
+ key_states = self.k_proj(hidden_states)
382
+ value_states = self.v_proj(hidden_states)
383
+
384
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
385
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
386
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
387
+
388
+ kv_seq_len = key_states.shape[-2]
389
+ if past_key_value is not None:
390
+ kv_seq_len += past_key_value[0].shape[-2]
391
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
392
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
393
+
394
+ if past_key_value is not None:
395
+ # reuse k, v, self_attention
396
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
397
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
398
+
399
+ past_key_value = (key_states, value_states) if use_cache else None
400
+
401
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
402
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
403
+
404
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
405
+
406
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
407
+ raise ValueError(
408
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
409
+ f" {attn_weights.size()}"
410
+ )
411
+
412
+ if attention_mask is not None:
413
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
414
+ raise ValueError(
415
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
416
+ )
417
+ attn_weights = attn_weights + attention_mask
418
+
419
+ # upcast attention to fp32
420
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
421
+ attn_output = torch.matmul(attn_weights, value_states)
422
+
423
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
424
+ raise ValueError(
425
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
426
+ f" {attn_output.size()}"
427
+ )
428
+
429
+ attn_output = attn_output.transpose(1, 2).contiguous()
430
+
431
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
432
+
433
+ if self.config.pretraining_tp > 1:
434
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
435
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
436
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
437
+ else:
438
+ attn_output = self.o_proj(attn_output)
439
+
440
+ if not output_attentions:
441
+ attn_weights = None
442
+
443
+ return attn_output, attn_weights, past_key_value
444
+
445
+
446
+ class LlamaFlashAttention2(LlamaAttention):
447
+ """
448
+ Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
449
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
450
+ flash attention and deal with padding tokens in case the input contains any of them.
451
+ """
452
+
453
+ def forward(
454
+ self,
455
+ hidden_states: torch.Tensor,
456
+ attention_mask: Optional[torch.LongTensor] = None,
457
+ position_ids: Optional[torch.LongTensor] = None,
458
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
459
+ output_attentions: bool = False,
460
+ use_cache: bool = False,
461
+ **kwargs,
462
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
463
+ # LlamaFlashAttention2 attention does not support output_attentions
464
+ if "padding_mask" in kwargs:
465
+ warnings.warn(
466
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
467
+ )
468
+
469
+ # overwrite attention_mask with padding_mask
470
+ attention_mask = kwargs.pop("padding_mask")
471
+
472
+ output_attentions = False
473
+
474
+ bsz, q_len, _ = hidden_states.size()
475
+
476
+ query_states = self.q_proj(hidden_states)
477
+ key_states = self.k_proj(hidden_states)
478
+ value_states = self.v_proj(hidden_states)
479
+
480
+ # Flash attention requires the input to have the shape
481
+ # batch_size x seq_length x head_dim x hidden_dim
482
+ # therefore we just need to keep the original shape
483
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
484
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
485
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
486
+
487
+ kv_seq_len = key_states.shape[-2]
488
+ if past_key_value is not None:
489
+ kv_seq_len += past_key_value[0].shape[-2]
490
+
491
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
492
+
493
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
494
+
495
+ if past_key_value is not None:
496
+ # reuse k, v, self_attention
497
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
498
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
499
+
500
+ past_key_value = (key_states, value_states) if use_cache else None
501
+
502
+ query_states = query_states.transpose(1, 2)
503
+ key_states = key_states.transpose(1, 2)
504
+ value_states = value_states.transpose(1, 2)
505
+
506
+ # TODO: llama does not have dropout in the config??
507
+ # It is recommended to use dropout with FA according to the docs
508
+ # when training.
509
+ dropout_rate = 0.0 # if not self.training else self.attn_dropout
510
+
511
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
512
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
513
+ # cast them back in the correct dtype just to be sure everything works as expected.
514
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
515
+ # in fp32. (LlamaRMSNorm handles it correctly)
516
+
517
+ input_dtype = query_states.dtype
518
+ if input_dtype == torch.float32:
519
+ # Handle the case where the model is quantized
520
+ if hasattr(self.config, "_pre_quantization_dtype"):
521
+ target_dtype = self.config._pre_quantization_dtype
522
+ else:
523
+ target_dtype = self.q_proj.weight.dtype
524
+
525
+ logger.warning_once(
526
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
527
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
528
+ f" {target_dtype}."
529
+ )
530
+
531
+ query_states = query_states.to(target_dtype)
532
+ key_states = key_states.to(target_dtype)
533
+ value_states = value_states.to(target_dtype)
534
+
535
+ attn_output = self._flash_attention_forward(
536
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
537
+ )
538
+
539
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
540
+ attn_output = self.o_proj(attn_output)
541
+
542
+ if not output_attentions:
543
+ attn_weights = None
544
+
545
+ return attn_output, attn_weights, past_key_value
546
+
547
+ def _flash_attention_forward(
548
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
549
+ ):
550
+ """
551
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
552
+ first unpad the input, then computes the attention scores and pad the final attention scores.
553
+
554
+ Args:
555
+ query_states (`torch.Tensor`):
556
+ Input query states to be passed to Flash Attention API
557
+ key_states (`torch.Tensor`):
558
+ Input key states to be passed to Flash Attention API
559
+ value_states (`torch.Tensor`):
560
+ Input value states to be passed to Flash Attention API
561
+ attention_mask (`torch.Tensor`):
562
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
563
+ position of padding tokens and 1 for the position of non-padding tokens.
564
+ dropout (`int`, *optional*):
565
+ Attention dropout
566
+ softmax_scale (`float`, *optional*):
567
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
568
+ """
569
+ # Contains at least one padding token in the sequence
570
+ if attention_mask is not None:
571
+ batch_size = query_states.shape[0]
572
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
573
+ query_states, key_states, value_states, attention_mask, query_length
574
+ )
575
+
576
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
577
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
578
+
579
+ attn_output_unpad = flash_attn_varlen_func(
580
+ query_states,
581
+ key_states,
582
+ value_states,
583
+ cu_seqlens_q=cu_seqlens_q,
584
+ cu_seqlens_k=cu_seqlens_k,
585
+ max_seqlen_q=max_seqlen_in_batch_q,
586
+ max_seqlen_k=max_seqlen_in_batch_k,
587
+ dropout_p=dropout,
588
+ softmax_scale=softmax_scale,
589
+ causal=self.is_causal,
590
+ )
591
+
592
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
593
+ else:
594
+ attn_output = flash_attn_func(
595
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=self.is_causal
596
+ )
597
+
598
+ return attn_output
599
+
600
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
601
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
602
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
603
+
604
+ key_layer = index_first_axis(
605
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
606
+ )
607
+ value_layer = index_first_axis(
608
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
609
+ )
610
+ if query_length == kv_seq_len:
611
+ query_layer = index_first_axis(
612
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
613
+ )
614
+ cu_seqlens_q = cu_seqlens_k
615
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
616
+ indices_q = indices_k
617
+ elif query_length == 1:
618
+ max_seqlen_in_batch_q = 1
619
+ cu_seqlens_q = torch.arange(
620
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
621
+ ) # There is a memcpy here, that is very bad.
622
+ indices_q = cu_seqlens_q[:-1]
623
+ query_layer = query_layer.squeeze(1)
624
+ else:
625
+ # The -q_len: slice assumes left padding.
626
+ attention_mask = attention_mask[:, -query_length:]
627
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
628
+
629
+ return (
630
+ query_layer,
631
+ key_layer,
632
+ value_layer,
633
+ indices_q,
634
+ (cu_seqlens_q, cu_seqlens_k),
635
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
636
+ )
637
+
638
+
639
+ class LlamaDecoderLayer(nn.Module):
640
+ def __init__(self, config: SparseLlamaConfig):
641
+ super().__init__()
642
+ self.hidden_size = config.hidden_size
643
+ self.self_attn = (
644
+ LlamaAttention(config=config)
645
+ if not getattr(config, "_flash_attn_2_enabled", False)
646
+ else LlamaFlashAttention2(config=config)
647
+ )
648
+ self.mlp = SparseLlamaMLP(config)
649
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
650
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
651
+
652
+ def forward(
653
+ self,
654
+ hidden_states: torch.Tensor,
655
+ attention_mask: Optional[torch.Tensor] = None,
656
+ position_ids: Optional[torch.LongTensor] = None,
657
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
658
+ output_attentions: Optional[bool] = False,
659
+ use_cache: Optional[bool] = False,
660
+ **kwargs,
661
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
662
+ """
663
+ Args:
664
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
665
+ attention_mask (`torch.FloatTensor`, *optional*):
666
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
667
+ query_sequence_length, key_sequence_length)` if default attention is used.
668
+ output_attentions (`bool`, *optional*):
669
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
670
+ returned tensors for more detail.
671
+ use_cache (`bool`, *optional*):
672
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
673
+ (see `past_key_values`).
674
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
675
+ """
676
+ if "padding_mask" in kwargs:
677
+ warnings.warn(
678
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
679
+ )
680
+
681
+ residual = hidden_states
682
+
683
+ hidden_states = self.input_layernorm(hidden_states)
684
+
685
+ # Self Attention
686
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
687
+ hidden_states=hidden_states,
688
+ attention_mask=attention_mask,
689
+ position_ids=position_ids,
690
+ past_key_value=past_key_value,
691
+ output_attentions=output_attentions,
692
+ use_cache=use_cache,
693
+ **kwargs,
694
+ )
695
+ hidden_states = residual + hidden_states
696
+
697
+ # Fully Connected
698
+ residual = hidden_states
699
+ hidden_states = self.post_attention_layernorm(hidden_states)
700
+ hidden_states = self.mlp(hidden_states)
701
+ hidden_states = residual + hidden_states
702
+
703
+ outputs = (hidden_states,)
704
+
705
+ if output_attentions:
706
+ outputs += (self_attn_weights,)
707
+
708
+ if use_cache:
709
+ outputs += (present_key_value,)
710
+
711
+ return outputs
712
+
713
+
714
+ LLAMA_START_DOCSTRING = r"""
715
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
716
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
717
+ etc.)
718
+
719
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
720
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
721
+ and behavior.
722
+
723
+ Parameters:
724
+ config ([`LlamaConfig`]):
725
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
726
+ load the weights associated with the model, only the configuration. Check out the
727
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
728
+ """
729
+
730
+
731
+ @add_start_docstrings(
732
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
733
+ LLAMA_START_DOCSTRING,
734
+ )
735
+ class SparseLlamaPreTrainedModel(PreTrainedModel):
736
+ config_class = SparseLlamaConfig
737
+ base_model_prefix = "model"
738
+ supports_gradient_checkpointing = True
739
+ _no_split_modules = ["LlamaDecoderLayer"]
740
+ _skip_keys_device_placement = "past_key_values"
741
+ _supports_flash_attn_2 = True
742
+
743
+ def _init_weights(self, module):
744
+ std = self.config.initializer_range
745
+ if isinstance(module, nn.Linear):
746
+ module.weight.data.normal_(mean=0.0, std=std)
747
+ if module.bias is not None:
748
+ module.bias.data.zero_()
749
+ elif isinstance(module, nn.Embedding):
750
+ module.weight.data.normal_(mean=0.0, std=std)
751
+ if module.padding_idx is not None:
752
+ module.weight.data[module.padding_idx].zero_()
753
+
754
+
755
+ LLAMA_INPUTS_DOCSTRING = r"""
756
+ Args:
757
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
758
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
759
+ it.
760
+
761
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
762
+ [`PreTrainedTokenizer.__call__`] for details.
763
+
764
+ [What are input IDs?](../glossary#input-ids)
765
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
766
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
767
+
768
+ - 1 for tokens that are **not masked**,
769
+ - 0 for tokens that are **masked**.
770
+
771
+ [What are attention masks?](../glossary#attention-mask)
772
+
773
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
774
+ [`PreTrainedTokenizer.__call__`] for details.
775
+
776
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
777
+ `past_key_values`).
778
+
779
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
780
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
781
+ information on the default strategy.
782
+
783
+ - 1 indicates the head is **not masked**,
784
+ - 0 indicates the head is **masked**.
785
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
786
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
787
+ config.n_positions - 1]`.
788
+
789
+ [What are position IDs?](../glossary#position-ids)
790
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
791
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
792
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
793
+ `(batch_size, num_heads, decoder_sequence_length, embed_size_per_head)`.
794
+
795
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
796
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
797
+
798
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
799
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
800
+ of shape `(batch_size, sequence_length)`.
801
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
802
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
803
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
804
+ model's internal embedding lookup matrix.
805
+ use_cache (`bool`, *optional*):
806
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
807
+ `past_key_values`).
808
+ output_attentions (`bool`, *optional*):
809
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
810
+ tensors for more detail.
811
+ output_hidden_states (`bool`, *optional*):
812
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
813
+ more detail.
814
+ return_dict (`bool`, *optional*):
815
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
816
+ """
817
+
818
+
819
+ @add_start_docstrings(
820
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
821
+ LLAMA_START_DOCSTRING,
822
+ )
823
+ class SparseLlamaModel(SparseLlamaPreTrainedModel):
824
+ """
825
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
826
+
827
+ Args:
828
+ config: LlamaConfig
829
+ """
830
+
831
+ def __init__(self, config: SparseLlamaConfig):
832
+ super().__init__(config)
833
+ self.padding_idx = config.pad_token_id
834
+ self.vocab_size = config.vocab_size
835
+
836
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
837
+ self.layers = nn.ModuleList([LlamaDecoderLayer(config) for _ in range(config.num_hidden_layers)])
838
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
839
+
840
+ self.gradient_checkpointing = False
841
+ # Initialize weights and apply final processing
842
+ self.post_init()
843
+
844
+ def get_input_embeddings(self):
845
+ return self.embed_tokens
846
+
847
+ def set_input_embeddings(self, value):
848
+ self.embed_tokens = value
849
+
850
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
851
+ def forward(
852
+ self,
853
+ input_ids: torch.LongTensor = None,
854
+ attention_mask: Optional[torch.Tensor] = None,
855
+ position_ids: Optional[torch.LongTensor] = None,
856
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
857
+ inputs_embeds: Optional[torch.FloatTensor] = None,
858
+ use_cache: Optional[bool] = None,
859
+ output_attentions: Optional[bool] = None,
860
+ output_hidden_states: Optional[bool] = None,
861
+ return_dict: Optional[bool] = None,
862
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
863
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
864
+ output_hidden_states = (
865
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
866
+ )
867
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
868
+
869
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
870
+
871
+ # retrieve input_ids and inputs_embeds
872
+ if input_ids is not None and inputs_embeds is not None:
873
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
874
+ elif input_ids is not None:
875
+ batch_size, seq_length = input_ids.shape[:2]
876
+ elif inputs_embeds is not None:
877
+ batch_size, seq_length = inputs_embeds.shape[:2]
878
+ else:
879
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
880
+
881
+ past_key_values_length = 0
882
+ if past_key_values is not None:
883
+ past_key_values_length = past_key_values[0][0].shape[2]
884
+
885
+ if position_ids is None:
886
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
887
+ position_ids = torch.arange(
888
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
889
+ )
890
+ position_ids = position_ids.unsqueeze(0)
891
+
892
+ if inputs_embeds is None:
893
+ inputs_embeds = self.embed_tokens(input_ids)
894
+
895
+ if getattr(self.config, "_flash_attn_2_enabled", False):
896
+ # 2d mask is passed through the layers
897
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
898
+ else:
899
+ # 4d mask is passed through the layers
900
+ attention_mask = _prepare_4d_causal_attention_mask(
901
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
902
+ )
903
+
904
+ # embed positions
905
+ hidden_states = inputs_embeds
906
+
907
+ if self.gradient_checkpointing and self.training:
908
+ if use_cache:
909
+ logger.warning_once(
910
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
911
+ )
912
+ use_cache = False
913
+
914
+ # decoder layers
915
+ all_hidden_states = () if output_hidden_states else None
916
+ all_self_attns = () if output_attentions else None
917
+ next_decoder_cache = () if use_cache else None
918
+
919
+ for idx, decoder_layer in enumerate(self.layers):
920
+ if output_hidden_states:
921
+ all_hidden_states += (hidden_states,)
922
+
923
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
924
+
925
+ if self.gradient_checkpointing and self.training:
926
+ layer_outputs = self._gradient_checkpointing_func(
927
+ decoder_layer.__call__,
928
+ hidden_states,
929
+ attention_mask,
930
+ position_ids,
931
+ past_key_value,
932
+ output_attentions,
933
+ use_cache,
934
+ )
935
+ else:
936
+ layer_outputs = decoder_layer(
937
+ hidden_states,
938
+ attention_mask=attention_mask,
939
+ position_ids=position_ids,
940
+ past_key_value=past_key_value,
941
+ output_attentions=output_attentions,
942
+ use_cache=use_cache,
943
+ )
944
+
945
+ hidden_states = layer_outputs[0]
946
+
947
+ if use_cache:
948
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
949
+
950
+ if output_attentions:
951
+ all_self_attns += (layer_outputs[1],)
952
+
953
+ hidden_states = self.norm(hidden_states)
954
+
955
+ # add hidden states from the last decoder layer
956
+ if output_hidden_states:
957
+ all_hidden_states += (hidden_states,)
958
+
959
+ next_cache = next_decoder_cache if use_cache else None
960
+ if not return_dict:
961
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
962
+ return BaseModelOutputWithPast(
963
+ last_hidden_state=hidden_states,
964
+ past_key_values=next_cache,
965
+ hidden_states=all_hidden_states,
966
+ attentions=all_self_attns,
967
+ )
968
+
969
+
970
+ class SparseLlamaForCausalLM(SparseLlamaPreTrainedModel):
971
+ _tied_weights_keys = ["lm_head.weight"]
972
+
973
+ def __init__(self, config):
974
+ super().__init__(config)
975
+ self.model = SparseLlamaModel(config)
976
+ self.vocab_size = config.vocab_size
977
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
978
+
979
+ # Initialize weights and apply final processing
980
+ self.post_init()
981
+
982
+ def get_input_embeddings(self):
983
+ return self.model.embed_tokens
984
+
985
+ def set_input_embeddings(self, value):
986
+ self.model.embed_tokens = value
987
+
988
+ def get_output_embeddings(self):
989
+ return self.lm_head
990
+
991
+ def set_output_embeddings(self, new_embeddings):
992
+ self.lm_head = new_embeddings
993
+
994
+ def set_decoder(self, decoder):
995
+ self.model = decoder
996
+
997
+ def get_decoder(self):
998
+ return self.model
999
+
1000
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1001
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1002
+ def forward(
1003
+ self,
1004
+ input_ids: torch.LongTensor = None,
1005
+ attention_mask: Optional[torch.Tensor] = None,
1006
+ position_ids: Optional[torch.LongTensor] = None,
1007
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1008
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1009
+ labels: Optional[torch.LongTensor] = None,
1010
+ use_cache: Optional[bool] = None,
1011
+ output_attentions: Optional[bool] = None,
1012
+ output_hidden_states: Optional[bool] = None,
1013
+ return_dict: Optional[bool] = None,
1014
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1015
+ r"""
1016
+ Args:
1017
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1018
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1019
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1020
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1021
+
1022
+ Returns:
1023
+
1024
+ Example:
1025
+
1026
+ ```python
1027
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
1028
+
1029
+ >>> model = SparseLlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1030
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1031
+
1032
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1033
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1034
+
1035
+ >>> # Generate
1036
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1037
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1038
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1039
+ ```"""
1040
+
1041
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1042
+ output_hidden_states = (
1043
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1044
+ )
1045
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1046
+
1047
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1048
+ outputs = self.model(
1049
+ input_ids=input_ids,
1050
+ attention_mask=attention_mask,
1051
+ position_ids=position_ids,
1052
+ past_key_values=past_key_values,
1053
+ inputs_embeds=inputs_embeds,
1054
+ use_cache=use_cache,
1055
+ output_attentions=output_attentions,
1056
+ output_hidden_states=output_hidden_states,
1057
+ return_dict=return_dict,
1058
+ )
1059
+
1060
+ hidden_states = outputs[0]
1061
+ if self.config.pretraining_tp > 1:
1062
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1063
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1064
+ logits = torch.cat(logits, dim=-1)
1065
+ else:
1066
+ logits = self.lm_head(hidden_states)
1067
+ logits = logits.float()
1068
+
1069
+ loss = None
1070
+ if labels is not None:
1071
+ # Shift so that tokens < n predict n
1072
+ shift_logits = logits[..., :-1, :].contiguous()
1073
+ shift_labels = labels[..., 1:].contiguous()
1074
+ # Flatten the tokens
1075
+ loss_fct = CrossEntropyLoss()
1076
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1077
+ shift_labels = shift_labels.view(-1)
1078
+ # Enable model parallelism
1079
+ shift_labels = shift_labels.to(shift_logits.device)
1080
+ loss = loss_fct(shift_logits, shift_labels)
1081
+
1082
+ if not return_dict:
1083
+ output = (logits,) + outputs[1:]
1084
+ return (loss,) + output if loss is not None else output
1085
+
1086
+ return CausalLMOutputWithPast(
1087
+ loss=loss,
1088
+ logits=logits,
1089
+ past_key_values=outputs.past_key_values,
1090
+ hidden_states=outputs.hidden_states,
1091
+ attentions=outputs.attentions,
1092
+ )
1093
+
1094
+ def prepare_inputs_for_generation(
1095
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1096
+ ):
1097
+ if past_key_values is not None:
1098
+ past_length = past_key_values[0][0].shape[2]
1099
+
1100
+ # Some generation methods already pass only the last input ID
1101
+ if input_ids.shape[1] > past_length:
1102
+ remove_prefix_length = past_length
1103
+ else:
1104
+ # Default to old behavior: keep only final ID
1105
+ remove_prefix_length = input_ids.shape[1] - 1
1106
+
1107
+ input_ids = input_ids[:, remove_prefix_length:]
1108
+
1109
+ position_ids = kwargs.get("position_ids", None)
1110
+ if attention_mask is not None and position_ids is None:
1111
+ # create position_ids on the fly for batch generation
1112
+ position_ids = attention_mask.long().cumsum(-1) - 1
1113
+ position_ids.masked_fill_(attention_mask == 0, 1)
1114
+ if past_key_values:
1115
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1116
+
1117
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1118
+ if inputs_embeds is not None and past_key_values is None:
1119
+ model_inputs = {"inputs_embeds": inputs_embeds}
1120
+ else:
1121
+ model_inputs = {"input_ids": input_ids}
1122
+
1123
+ model_inputs.update(
1124
+ {
1125
+ "position_ids": position_ids,
1126
+ "past_key_values": past_key_values,
1127
+ "use_cache": kwargs.get("use_cache"),
1128
+ "attention_mask": attention_mask,
1129
+ }
1130
+ )
1131
+ return model_inputs
1132
+
1133
+ @staticmethod
1134
+ def _reorder_cache(past_key_values, beam_idx):
1135
+ reordered_past = ()
1136
+ for layer_past in past_key_values:
1137
+ reordered_past += (
1138
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1139
+ )
1140
+ return reordered_past
1141
+
1142
+
1143
+ @add_start_docstrings(
1144
+ """
1145
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
1146
+
1147
+ [`SparseLlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1148
+ (e.g. GPT-2) do.
1149
+
1150
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1151
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1152
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1153
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1154
+ each row of the batch).
1155
+ """,
1156
+ LLAMA_START_DOCSTRING,
1157
+ )
1158
+ class SparseLlamaForSequenceClassification(SparseLlamaPreTrainedModel):
1159
+ def __init__(self, config):
1160
+ super().__init__(config)
1161
+ self.num_labels = config.num_labels
1162
+ self.model = SparseLlamaModel(config)
1163
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1164
+
1165
+ # Initialize weights and apply final processing
1166
+ self.post_init()
1167
+
1168
+ def get_input_embeddings(self):
1169
+ return self.model.embed_tokens
1170
+
1171
+ def set_input_embeddings(self, value):
1172
+ self.model.embed_tokens = value
1173
+
1174
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1175
+ def forward(
1176
+ self,
1177
+ input_ids: torch.LongTensor = None,
1178
+ attention_mask: Optional[torch.Tensor] = None,
1179
+ position_ids: Optional[torch.LongTensor] = None,
1180
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1181
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1182
+ labels: Optional[torch.LongTensor] = None,
1183
+ use_cache: Optional[bool] = None,
1184
+ output_attentions: Optional[bool] = None,
1185
+ output_hidden_states: Optional[bool] = None,
1186
+ return_dict: Optional[bool] = None,
1187
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1188
+ r"""
1189
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1190
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1191
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1192
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1193
+ """
1194
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1195
+
1196
+ transformer_outputs = self.model(
1197
+ input_ids,
1198
+ attention_mask=attention_mask,
1199
+ position_ids=position_ids,
1200
+ past_key_values=past_key_values,
1201
+ inputs_embeds=inputs_embeds,
1202
+ use_cache=use_cache,
1203
+ output_attentions=output_attentions,
1204
+ output_hidden_states=output_hidden_states,
1205
+ return_dict=return_dict,
1206
+ )
1207
+ hidden_states = transformer_outputs[0]
1208
+ logits = self.score(hidden_states)
1209
+
1210
+ if input_ids is not None:
1211
+ batch_size = input_ids.shape[0]
1212
+ else:
1213
+ batch_size = inputs_embeds.shape[0]
1214
+
1215
+ if self.config.pad_token_id is None and batch_size != 1:
1216
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1217
+ if self.config.pad_token_id is None:
1218
+ sequence_lengths = -1
1219
+ else:
1220
+ if input_ids is not None:
1221
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).long().argmax(-1) - 1).to(
1222
+ logits.device
1223
+ )
1224
+ else:
1225
+ sequence_lengths = -1
1226
+
1227
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1228
+
1229
+ loss = None
1230
+ if labels is not None:
1231
+ labels = labels.to(logits.device)
1232
+ if self.config.problem_type is None:
1233
+ if self.num_labels == 1:
1234
+ self.config.problem_type = "regression"
1235
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1236
+ self.config.problem_type = "single_label_classification"
1237
+ else:
1238
+ self.config.problem_type = "multi_label_classification"
1239
+
1240
+ if self.config.problem_type == "regression":
1241
+ loss_fct = MSELoss()
1242
+ if self.num_labels == 1:
1243
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1244
+ else:
1245
+ loss = loss_fct(pooled_logits, labels)
1246
+ elif self.config.problem_type == "single_label_classification":
1247
+ loss_fct = CrossEntropyLoss()
1248
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1249
+ elif self.config.problem_type == "multi_label_classification":
1250
+ loss_fct = BCEWithLogitsLoss()
1251
+ loss = loss_fct(pooled_logits, labels)
1252
+ if not return_dict:
1253
+ output = (pooled_logits,) + transformer_outputs[1:]
1254
+ return ((loss,) + output) if loss is not None else output
1255
+
1256
+ return SequenceClassifierOutputWithPast(
1257
+ loss=loss,
1258
+ logits=pooled_logits,
1259
+ past_key_values=transformer_outputs.past_key_values,
1260
+ hidden_states=transformer_outputs.hidden_states,
1261
+ attentions=transformer_outputs.attentions,
1262
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "</s>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "unk_token": {
17
+ "content": "<unk>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ }
23
+ }
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347
3
+ size 499723
tokenizer_config.json ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "bos_token": {
5
+ "__type": "AddedToken",
6
+ "content": "<s>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false
11
+ },
12
+ "clean_up_tokenization_spaces": false,
13
+ "eos_token": {
14
+ "__type": "AddedToken",
15
+ "content": "</s>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false
20
+ },
21
+ "legacy": false,
22
+ "model_max_length": 1000000000000000019884624838656,
23
+ "pad_token": null,
24
+ "padding_side": "right",
25
+ "sp_model_kwargs": {},
26
+ "tokenizer_class": "LlamaTokenizer",
27
+ "unk_token": {
28
+ "__type": "AddedToken",
29
+ "content": "<unk>",
30
+ "lstrip": false,
31
+ "normalized": false,
32
+ "rstrip": false,
33
+ "single_word": false
34
+ }
35
+ }