xiaodobg commited on
Commit
2cdf6e3
1 Parent(s): 2d6467c

Upload 9 files

Browse files
config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/root/workspace/models/cebor/cebor-2B-dpo-bf16",
3
+ "architectures": [
4
+ "CerboAIForCausalLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_cerboai.CerboAIConfig",
10
+ "AutoModel": "modeling_cerboai.CerboAIForCausalLM",
11
+ "AutoModelForCausalLM": "modeling_cerboai.CerboAIForCausalLM",
12
+ "AutoModelForSeq2SeqLM": "modeling_cerboai.CerboAIForCausalLM",
13
+ "AutoModelForSequenceClassification": "modeling_cerboai.CerboAIForSequenceClassification"
14
+ },
15
+ "bos_token_id": 1,
16
+ "dim_model_base": 256,
17
+ "eos_token_id": 2,
18
+ "hidden_act": "silu",
19
+ "hidden_size": 2304,
20
+ "initializer_range": 0.1,
21
+ "intermediate_size": 5760,
22
+ "max_position_embeddings": 2048,
23
+ "model_type": "CerboAI",
24
+ "num_attention_heads": 36,
25
+ "num_hidden_layers": 40,
26
+ "num_key_value_heads": 36,
27
+ "pretraining_tp": 1,
28
+ "rms_norm_eps": 1e-05,
29
+ "rope_scaling": null,
30
+ "rope_theta": 10000.0,
31
+ "scale_depth": 1.4,
32
+ "scale_emb": 12,
33
+ "torch_dtype": "bfloat16",
34
+ "transformers_version": "4.41.2",
35
+ "use_cache": true,
36
+ "vocab_size": 122753
37
+ }
configuration_cerboai.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ # See the License for the specific language governing permissions and
12
+ # limitations under the License.
13
+ """ CerboAI model configuration"""
14
+
15
+ from transformers.configuration_utils import PretrainedConfig
16
+ from transformers.utils import logging
17
+
18
+
19
+ logger = logging.get_logger(__name__)
20
+
21
+ CerboAI_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
22
+
23
+
24
+ class CerboAIConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`CerboAIModel`]. It is used to instantiate an CerboAI
27
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
28
+ defaults will yield a similar configuration to that of the CerboAI-7B.
29
+
30
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
31
+ documentation from [`PretrainedConfig`] for more information.
32
+
33
+
34
+ Args:
35
+ vocab_size (`int`, *optional*, defaults to 32000):
36
+ Vocabulary size of the CerboAI model. Defines the number of different tokens that can be represented by the
37
+ `inputs_ids` passed when calling [`CerboAIModel`]
38
+ hidden_size (`int`, *optional*, defaults to 4096):
39
+ Dimension of the hidden representations.
40
+ intermediate_size (`int`, *optional*, defaults to 11008):
41
+ Dimension of the MLP representations.
42
+ num_hidden_layers (`int`, *optional*, defaults to 32):
43
+ Number of hidden layers in the Transformer decoder.
44
+ num_attention_heads (`int`, *optional*, defaults to 32):
45
+ Number of attention heads for each attention layer in the Transformer decoder.
46
+ num_key_value_heads (`int`, *optional*):
47
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
48
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
49
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
50
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
51
+ by meanpooling all the original heads within that group. For more details checkout [this
52
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
53
+ `num_attention_heads`.
54
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
55
+ The non-linear activation function (function or string) in the decoder.
56
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
57
+ The maximum sequence length that this model might ever be used with. CerboAI 1 supports up to 2048 tokens,
58
+ CerboAI 2 up to 4096, CodeCerboAI up to 16384.
59
+ initializer_range (`float`, *optional*, defaults to 0.02):
60
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
61
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
62
+ The epsilon used by the rms normalization layers.
63
+ use_cache (`bool`, *optional*, defaults to `True`):
64
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
65
+ relevant if `config.is_decoder=True`.
66
+ pad_token_id (`int`, *optional*):
67
+ Padding token id.
68
+ bos_token_id (`int`, *optional*, defaults to 1):
69
+ Beginning of stream token id.
70
+ eos_token_id (`int`, *optional*, defaults to 2):
71
+ End of stream token id.
72
+ pretraining_tp (`int`, *optional*, defaults to 1):
73
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
74
+ document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
75
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
76
+ issue](https://github.com/pytorch/pytorch/issues/76232).
77
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
78
+ Whether to tie weight embeddings
79
+ rope_theta (`float`, *optional*, defaults to 10000.0):
80
+ The base period of the RoPE embeddings.
81
+ rope_scaling (`Dict`, *optional*):
82
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
83
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
84
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
85
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
86
+ these scaling strategies behave:
87
+ https://www.reddit.com/r/LocalCerboAI/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
88
+ experimental feature, subject to breaking API changes in future versions.
89
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
90
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
91
+ attention_dropout (`float`, *optional*, defaults to 0.0):
92
+ The dropout ratio for the attention probabilities.
93
+
94
+ """
95
+
96
+ model_type = "CerboAI"
97
+ keys_to_ignore_at_inference = ["past_key_values"]
98
+
99
+ def __init__(
100
+ self,
101
+ vocab_size=32000,
102
+ hidden_size=4096,
103
+ intermediate_size=11008,
104
+ num_hidden_layers=32,
105
+ num_attention_heads=32,
106
+ num_key_value_heads=None,
107
+ hidden_act="silu",
108
+ max_position_embeddings=2048,
109
+ initializer_range=0.02,
110
+ rms_norm_eps=1e-6,
111
+ use_cache=True,
112
+ pad_token_id=None,
113
+ bos_token_id=1,
114
+ eos_token_id=2,
115
+ pretraining_tp=1,
116
+ tie_word_embeddings=True,
117
+ rope_theta=10000.0,
118
+ rope_scaling=None,
119
+ attention_bias=False,
120
+ attention_dropout=0.0,
121
+ scale_emb=1,
122
+ dim_model_base=1,
123
+ scale_depth=1,
124
+ **kwargs,
125
+ ):
126
+ self.vocab_size = vocab_size
127
+ self.max_position_embeddings = max_position_embeddings
128
+ self.hidden_size = hidden_size
129
+ self.intermediate_size = intermediate_size
130
+ self.num_hidden_layers = num_hidden_layers
131
+ self.num_attention_heads = num_attention_heads
132
+
133
+ # for backward compatibility
134
+ if num_key_value_heads is None:
135
+ num_key_value_heads = num_attention_heads
136
+
137
+ self.num_key_value_heads = num_key_value_heads
138
+ self.hidden_act = hidden_act
139
+ self.initializer_range = initializer_range
140
+ self.rms_norm_eps = rms_norm_eps
141
+ self.pretraining_tp = pretraining_tp
142
+ self.use_cache = use_cache
143
+ self.rope_theta = rope_theta
144
+ self.rope_scaling = rope_scaling
145
+ self._rope_scaling_validation()
146
+ self.attention_bias = attention_bias
147
+ self.attention_dropout = attention_dropout
148
+ self.scale_emb = scale_emb
149
+ self.dim_model_base = dim_model_base
150
+ self.scale_depth = scale_depth
151
+
152
+ super().__init__(
153
+ pad_token_id=pad_token_id,
154
+ bos_token_id=bos_token_id,
155
+ eos_token_id=eos_token_id,
156
+ tie_word_embeddings=tie_word_embeddings,
157
+ **kwargs,
158
+ )
159
+ try:
160
+ import flash_attn
161
+
162
+ self._attn_implementation = "flash_attention_2"
163
+ except:
164
+ pass
165
+
166
+ def _rope_scaling_validation(self):
167
+ """
168
+ Validate the `rope_scaling` configuration.
169
+ """
170
+ if self.rope_scaling is None:
171
+ return
172
+
173
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
174
+ raise ValueError(
175
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
176
+ f"got {self.rope_scaling}"
177
+ )
178
+ rope_scaling_type = self.rope_scaling.get("type", None)
179
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
180
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
181
+ raise ValueError(
182
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
183
+ )
184
+ if (
185
+ rope_scaling_factor is None
186
+ or not isinstance(rope_scaling_factor, float)
187
+ or rope_scaling_factor <= 1.0
188
+ ):
189
+ raise ValueError(
190
+ f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}"
191
+ )
generation_config.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 1,
3
+ "do_sample": true,
4
+ "eos_token_id": 2,
5
+ "temperature": 0.8,
6
+ "top_p": 0.8,
7
+ "transformers_version": "4.41.2"
8
+ }
model.safetensors.index.json ADDED
@@ -0,0 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 5449761792
4
+ },
5
+ "weight_map": {
6
+ "model.embed_tokens.weight": "model-00001-of-00006.safetensors",
7
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00006.safetensors",
8
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
9
+ "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00006.safetensors",
10
+ "model.layers.0.mlp.up_proj.weight": "model-00001-of-00006.safetensors",
11
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00006.safetensors",
12
+ "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00006.safetensors",
13
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
14
+ "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00006.safetensors",
15
+ "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00006.safetensors",
16
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00006.safetensors",
17
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
18
+ "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00006.safetensors",
19
+ "model.layers.1.mlp.up_proj.weight": "model-00001-of-00006.safetensors",
20
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00006.safetensors",
21
+ "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00006.safetensors",
22
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
23
+ "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00006.safetensors",
24
+ "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00006.safetensors",
25
+ "model.layers.10.input_layernorm.weight": "model-00002-of-00006.safetensors",
26
+ "model.layers.10.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
27
+ "model.layers.10.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
28
+ "model.layers.10.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
29
+ "model.layers.10.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
30
+ "model.layers.10.self_attn.k_proj.weight": "model-00002-of-00006.safetensors",
31
+ "model.layers.10.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
32
+ "model.layers.10.self_attn.q_proj.weight": "model-00002-of-00006.safetensors",
33
+ "model.layers.10.self_attn.v_proj.weight": "model-00002-of-00006.safetensors",
34
+ "model.layers.11.input_layernorm.weight": "model-00003-of-00006.safetensors",
35
+ "model.layers.11.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
36
+ "model.layers.11.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
37
+ "model.layers.11.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
38
+ "model.layers.11.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
39
+ "model.layers.11.self_attn.k_proj.weight": "model-00002-of-00006.safetensors",
40
+ "model.layers.11.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
41
+ "model.layers.11.self_attn.q_proj.weight": "model-00002-of-00006.safetensors",
42
+ "model.layers.11.self_attn.v_proj.weight": "model-00002-of-00006.safetensors",
43
+ "model.layers.12.input_layernorm.weight": "model-00003-of-00006.safetensors",
44
+ "model.layers.12.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
45
+ "model.layers.12.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
46
+ "model.layers.12.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
47
+ "model.layers.12.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
48
+ "model.layers.12.self_attn.k_proj.weight": "model-00003-of-00006.safetensors",
49
+ "model.layers.12.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
50
+ "model.layers.12.self_attn.q_proj.weight": "model-00003-of-00006.safetensors",
51
+ "model.layers.12.self_attn.v_proj.weight": "model-00003-of-00006.safetensors",
52
+ "model.layers.13.input_layernorm.weight": "model-00003-of-00006.safetensors",
53
+ "model.layers.13.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
54
+ "model.layers.13.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
55
+ "model.layers.13.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
56
+ "model.layers.13.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
57
+ "model.layers.13.self_attn.k_proj.weight": "model-00003-of-00006.safetensors",
58
+ "model.layers.13.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
59
+ "model.layers.13.self_attn.q_proj.weight": "model-00003-of-00006.safetensors",
60
+ "model.layers.13.self_attn.v_proj.weight": "model-00003-of-00006.safetensors",
61
+ "model.layers.14.input_layernorm.weight": "model-00003-of-00006.safetensors",
62
+ "model.layers.14.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
63
+ "model.layers.14.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
64
+ "model.layers.14.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
65
+ "model.layers.14.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
66
+ "model.layers.14.self_attn.k_proj.weight": "model-00003-of-00006.safetensors",
67
+ "model.layers.14.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
68
+ "model.layers.14.self_attn.q_proj.weight": "model-00003-of-00006.safetensors",
69
+ "model.layers.14.self_attn.v_proj.weight": "model-00003-of-00006.safetensors",
70
+ "model.layers.15.input_layernorm.weight": "model-00003-of-00006.safetensors",
71
+ "model.layers.15.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
72
+ "model.layers.15.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
73
+ "model.layers.15.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
74
+ "model.layers.15.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
75
+ "model.layers.15.self_attn.k_proj.weight": "model-00003-of-00006.safetensors",
76
+ "model.layers.15.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
77
+ "model.layers.15.self_attn.q_proj.weight": "model-00003-of-00006.safetensors",
78
+ "model.layers.15.self_attn.v_proj.weight": "model-00003-of-00006.safetensors",
79
+ "model.layers.16.input_layernorm.weight": "model-00003-of-00006.safetensors",
80
+ "model.layers.16.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
81
+ "model.layers.16.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
82
+ "model.layers.16.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
83
+ "model.layers.16.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
84
+ "model.layers.16.self_attn.k_proj.weight": "model-00003-of-00006.safetensors",
85
+ "model.layers.16.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
86
+ "model.layers.16.self_attn.q_proj.weight": "model-00003-of-00006.safetensors",
87
+ "model.layers.16.self_attn.v_proj.weight": "model-00003-of-00006.safetensors",
88
+ "model.layers.17.input_layernorm.weight": "model-00003-of-00006.safetensors",
89
+ "model.layers.17.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
90
+ "model.layers.17.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
91
+ "model.layers.17.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
92
+ "model.layers.17.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
93
+ "model.layers.17.self_attn.k_proj.weight": "model-00003-of-00006.safetensors",
94
+ "model.layers.17.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
95
+ "model.layers.17.self_attn.q_proj.weight": "model-00003-of-00006.safetensors",
96
+ "model.layers.17.self_attn.v_proj.weight": "model-00003-of-00006.safetensors",
97
+ "model.layers.18.input_layernorm.weight": "model-00003-of-00006.safetensors",
98
+ "model.layers.18.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
99
+ "model.layers.18.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
100
+ "model.layers.18.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
101
+ "model.layers.18.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
102
+ "model.layers.18.self_attn.k_proj.weight": "model-00003-of-00006.safetensors",
103
+ "model.layers.18.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
104
+ "model.layers.18.self_attn.q_proj.weight": "model-00003-of-00006.safetensors",
105
+ "model.layers.18.self_attn.v_proj.weight": "model-00003-of-00006.safetensors",
106
+ "model.layers.19.input_layernorm.weight": "model-00004-of-00006.safetensors",
107
+ "model.layers.19.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
108
+ "model.layers.19.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
109
+ "model.layers.19.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
110
+ "model.layers.19.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
111
+ "model.layers.19.self_attn.k_proj.weight": "model-00003-of-00006.safetensors",
112
+ "model.layers.19.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
113
+ "model.layers.19.self_attn.q_proj.weight": "model-00003-of-00006.safetensors",
114
+ "model.layers.19.self_attn.v_proj.weight": "model-00003-of-00006.safetensors",
115
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00006.safetensors",
116
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
117
+ "model.layers.2.mlp.gate_proj.weight": "model-00001-of-00006.safetensors",
118
+ "model.layers.2.mlp.up_proj.weight": "model-00001-of-00006.safetensors",
119
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00006.safetensors",
120
+ "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00006.safetensors",
121
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
122
+ "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00006.safetensors",
123
+ "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00006.safetensors",
124
+ "model.layers.20.input_layernorm.weight": "model-00004-of-00006.safetensors",
125
+ "model.layers.20.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
126
+ "model.layers.20.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
127
+ "model.layers.20.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
128
+ "model.layers.20.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
129
+ "model.layers.20.self_attn.k_proj.weight": "model-00004-of-00006.safetensors",
130
+ "model.layers.20.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
131
+ "model.layers.20.self_attn.q_proj.weight": "model-00004-of-00006.safetensors",
132
+ "model.layers.20.self_attn.v_proj.weight": "model-00004-of-00006.safetensors",
133
+ "model.layers.21.input_layernorm.weight": "model-00004-of-00006.safetensors",
134
+ "model.layers.21.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
135
+ "model.layers.21.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
136
+ "model.layers.21.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
137
+ "model.layers.21.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
138
+ "model.layers.21.self_attn.k_proj.weight": "model-00004-of-00006.safetensors",
139
+ "model.layers.21.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
140
+ "model.layers.21.self_attn.q_proj.weight": "model-00004-of-00006.safetensors",
141
+ "model.layers.21.self_attn.v_proj.weight": "model-00004-of-00006.safetensors",
142
+ "model.layers.22.input_layernorm.weight": "model-00004-of-00006.safetensors",
143
+ "model.layers.22.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
144
+ "model.layers.22.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
145
+ "model.layers.22.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
146
+ "model.layers.22.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
147
+ "model.layers.22.self_attn.k_proj.weight": "model-00004-of-00006.safetensors",
148
+ "model.layers.22.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
149
+ "model.layers.22.self_attn.q_proj.weight": "model-00004-of-00006.safetensors",
150
+ "model.layers.22.self_attn.v_proj.weight": "model-00004-of-00006.safetensors",
151
+ "model.layers.23.input_layernorm.weight": "model-00004-of-00006.safetensors",
152
+ "model.layers.23.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
153
+ "model.layers.23.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
154
+ "model.layers.23.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
155
+ "model.layers.23.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
156
+ "model.layers.23.self_attn.k_proj.weight": "model-00004-of-00006.safetensors",
157
+ "model.layers.23.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
158
+ "model.layers.23.self_attn.q_proj.weight": "model-00004-of-00006.safetensors",
159
+ "model.layers.23.self_attn.v_proj.weight": "model-00004-of-00006.safetensors",
160
+ "model.layers.24.input_layernorm.weight": "model-00004-of-00006.safetensors",
161
+ "model.layers.24.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
162
+ "model.layers.24.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
163
+ "model.layers.24.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
164
+ "model.layers.24.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
165
+ "model.layers.24.self_attn.k_proj.weight": "model-00004-of-00006.safetensors",
166
+ "model.layers.24.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
167
+ "model.layers.24.self_attn.q_proj.weight": "model-00004-of-00006.safetensors",
168
+ "model.layers.24.self_attn.v_proj.weight": "model-00004-of-00006.safetensors",
169
+ "model.layers.25.input_layernorm.weight": "model-00004-of-00006.safetensors",
170
+ "model.layers.25.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
171
+ "model.layers.25.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
172
+ "model.layers.25.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
173
+ "model.layers.25.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
174
+ "model.layers.25.self_attn.k_proj.weight": "model-00004-of-00006.safetensors",
175
+ "model.layers.25.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
176
+ "model.layers.25.self_attn.q_proj.weight": "model-00004-of-00006.safetensors",
177
+ "model.layers.25.self_attn.v_proj.weight": "model-00004-of-00006.safetensors",
178
+ "model.layers.26.input_layernorm.weight": "model-00004-of-00006.safetensors",
179
+ "model.layers.26.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
180
+ "model.layers.26.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
181
+ "model.layers.26.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
182
+ "model.layers.26.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
183
+ "model.layers.26.self_attn.k_proj.weight": "model-00004-of-00006.safetensors",
184
+ "model.layers.26.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
185
+ "model.layers.26.self_attn.q_proj.weight": "model-00004-of-00006.safetensors",
186
+ "model.layers.26.self_attn.v_proj.weight": "model-00004-of-00006.safetensors",
187
+ "model.layers.27.input_layernorm.weight": "model-00005-of-00006.safetensors",
188
+ "model.layers.27.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
189
+ "model.layers.27.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
190
+ "model.layers.27.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
191
+ "model.layers.27.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
192
+ "model.layers.27.self_attn.k_proj.weight": "model-00004-of-00006.safetensors",
193
+ "model.layers.27.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
194
+ "model.layers.27.self_attn.q_proj.weight": "model-00004-of-00006.safetensors",
195
+ "model.layers.27.self_attn.v_proj.weight": "model-00004-of-00006.safetensors",
196
+ "model.layers.28.input_layernorm.weight": "model-00005-of-00006.safetensors",
197
+ "model.layers.28.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
198
+ "model.layers.28.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
199
+ "model.layers.28.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
200
+ "model.layers.28.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
201
+ "model.layers.28.self_attn.k_proj.weight": "model-00005-of-00006.safetensors",
202
+ "model.layers.28.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
203
+ "model.layers.28.self_attn.q_proj.weight": "model-00005-of-00006.safetensors",
204
+ "model.layers.28.self_attn.v_proj.weight": "model-00005-of-00006.safetensors",
205
+ "model.layers.29.input_layernorm.weight": "model-00005-of-00006.safetensors",
206
+ "model.layers.29.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
207
+ "model.layers.29.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
208
+ "model.layers.29.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
209
+ "model.layers.29.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
210
+ "model.layers.29.self_attn.k_proj.weight": "model-00005-of-00006.safetensors",
211
+ "model.layers.29.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
212
+ "model.layers.29.self_attn.q_proj.weight": "model-00005-of-00006.safetensors",
213
+ "model.layers.29.self_attn.v_proj.weight": "model-00005-of-00006.safetensors",
214
+ "model.layers.3.input_layernorm.weight": "model-00002-of-00006.safetensors",
215
+ "model.layers.3.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
216
+ "model.layers.3.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
217
+ "model.layers.3.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
218
+ "model.layers.3.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
219
+ "model.layers.3.self_attn.k_proj.weight": "model-00001-of-00006.safetensors",
220
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
221
+ "model.layers.3.self_attn.q_proj.weight": "model-00001-of-00006.safetensors",
222
+ "model.layers.3.self_attn.v_proj.weight": "model-00001-of-00006.safetensors",
223
+ "model.layers.30.input_layernorm.weight": "model-00005-of-00006.safetensors",
224
+ "model.layers.30.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
225
+ "model.layers.30.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
226
+ "model.layers.30.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
227
+ "model.layers.30.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
228
+ "model.layers.30.self_attn.k_proj.weight": "model-00005-of-00006.safetensors",
229
+ "model.layers.30.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
230
+ "model.layers.30.self_attn.q_proj.weight": "model-00005-of-00006.safetensors",
231
+ "model.layers.30.self_attn.v_proj.weight": "model-00005-of-00006.safetensors",
232
+ "model.layers.31.input_layernorm.weight": "model-00005-of-00006.safetensors",
233
+ "model.layers.31.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
234
+ "model.layers.31.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
235
+ "model.layers.31.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
236
+ "model.layers.31.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
237
+ "model.layers.31.self_attn.k_proj.weight": "model-00005-of-00006.safetensors",
238
+ "model.layers.31.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
239
+ "model.layers.31.self_attn.q_proj.weight": "model-00005-of-00006.safetensors",
240
+ "model.layers.31.self_attn.v_proj.weight": "model-00005-of-00006.safetensors",
241
+ "model.layers.32.input_layernorm.weight": "model-00005-of-00006.safetensors",
242
+ "model.layers.32.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
243
+ "model.layers.32.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
244
+ "model.layers.32.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
245
+ "model.layers.32.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
246
+ "model.layers.32.self_attn.k_proj.weight": "model-00005-of-00006.safetensors",
247
+ "model.layers.32.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
248
+ "model.layers.32.self_attn.q_proj.weight": "model-00005-of-00006.safetensors",
249
+ "model.layers.32.self_attn.v_proj.weight": "model-00005-of-00006.safetensors",
250
+ "model.layers.33.input_layernorm.weight": "model-00005-of-00006.safetensors",
251
+ "model.layers.33.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
252
+ "model.layers.33.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
253
+ "model.layers.33.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
254
+ "model.layers.33.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
255
+ "model.layers.33.self_attn.k_proj.weight": "model-00005-of-00006.safetensors",
256
+ "model.layers.33.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
257
+ "model.layers.33.self_attn.q_proj.weight": "model-00005-of-00006.safetensors",
258
+ "model.layers.33.self_attn.v_proj.weight": "model-00005-of-00006.safetensors",
259
+ "model.layers.34.input_layernorm.weight": "model-00005-of-00006.safetensors",
260
+ "model.layers.34.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
261
+ "model.layers.34.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
262
+ "model.layers.34.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
263
+ "model.layers.34.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
264
+ "model.layers.34.self_attn.k_proj.weight": "model-00005-of-00006.safetensors",
265
+ "model.layers.34.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
266
+ "model.layers.34.self_attn.q_proj.weight": "model-00005-of-00006.safetensors",
267
+ "model.layers.34.self_attn.v_proj.weight": "model-00005-of-00006.safetensors",
268
+ "model.layers.35.input_layernorm.weight": "model-00006-of-00006.safetensors",
269
+ "model.layers.35.mlp.down_proj.weight": "model-00006-of-00006.safetensors",
270
+ "model.layers.35.mlp.gate_proj.weight": "model-00006-of-00006.safetensors",
271
+ "model.layers.35.mlp.up_proj.weight": "model-00006-of-00006.safetensors",
272
+ "model.layers.35.post_attention_layernorm.weight": "model-00006-of-00006.safetensors",
273
+ "model.layers.35.self_attn.k_proj.weight": "model-00005-of-00006.safetensors",
274
+ "model.layers.35.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
275
+ "model.layers.35.self_attn.q_proj.weight": "model-00005-of-00006.safetensors",
276
+ "model.layers.35.self_attn.v_proj.weight": "model-00005-of-00006.safetensors",
277
+ "model.layers.36.input_layernorm.weight": "model-00006-of-00006.safetensors",
278
+ "model.layers.36.mlp.down_proj.weight": "model-00006-of-00006.safetensors",
279
+ "model.layers.36.mlp.gate_proj.weight": "model-00006-of-00006.safetensors",
280
+ "model.layers.36.mlp.up_proj.weight": "model-00006-of-00006.safetensors",
281
+ "model.layers.36.post_attention_layernorm.weight": "model-00006-of-00006.safetensors",
282
+ "model.layers.36.self_attn.k_proj.weight": "model-00006-of-00006.safetensors",
283
+ "model.layers.36.self_attn.o_proj.weight": "model-00006-of-00006.safetensors",
284
+ "model.layers.36.self_attn.q_proj.weight": "model-00006-of-00006.safetensors",
285
+ "model.layers.36.self_attn.v_proj.weight": "model-00006-of-00006.safetensors",
286
+ "model.layers.37.input_layernorm.weight": "model-00006-of-00006.safetensors",
287
+ "model.layers.37.mlp.down_proj.weight": "model-00006-of-00006.safetensors",
288
+ "model.layers.37.mlp.gate_proj.weight": "model-00006-of-00006.safetensors",
289
+ "model.layers.37.mlp.up_proj.weight": "model-00006-of-00006.safetensors",
290
+ "model.layers.37.post_attention_layernorm.weight": "model-00006-of-00006.safetensors",
291
+ "model.layers.37.self_attn.k_proj.weight": "model-00006-of-00006.safetensors",
292
+ "model.layers.37.self_attn.o_proj.weight": "model-00006-of-00006.safetensors",
293
+ "model.layers.37.self_attn.q_proj.weight": "model-00006-of-00006.safetensors",
294
+ "model.layers.37.self_attn.v_proj.weight": "model-00006-of-00006.safetensors",
295
+ "model.layers.38.input_layernorm.weight": "model-00006-of-00006.safetensors",
296
+ "model.layers.38.mlp.down_proj.weight": "model-00006-of-00006.safetensors",
297
+ "model.layers.38.mlp.gate_proj.weight": "model-00006-of-00006.safetensors",
298
+ "model.layers.38.mlp.up_proj.weight": "model-00006-of-00006.safetensors",
299
+ "model.layers.38.post_attention_layernorm.weight": "model-00006-of-00006.safetensors",
300
+ "model.layers.38.self_attn.k_proj.weight": "model-00006-of-00006.safetensors",
301
+ "model.layers.38.self_attn.o_proj.weight": "model-00006-of-00006.safetensors",
302
+ "model.layers.38.self_attn.q_proj.weight": "model-00006-of-00006.safetensors",
303
+ "model.layers.38.self_attn.v_proj.weight": "model-00006-of-00006.safetensors",
304
+ "model.layers.39.input_layernorm.weight": "model-00006-of-00006.safetensors",
305
+ "model.layers.39.mlp.down_proj.weight": "model-00006-of-00006.safetensors",
306
+ "model.layers.39.mlp.gate_proj.weight": "model-00006-of-00006.safetensors",
307
+ "model.layers.39.mlp.up_proj.weight": "model-00006-of-00006.safetensors",
308
+ "model.layers.39.post_attention_layernorm.weight": "model-00006-of-00006.safetensors",
309
+ "model.layers.39.self_attn.k_proj.weight": "model-00006-of-00006.safetensors",
310
+ "model.layers.39.self_attn.o_proj.weight": "model-00006-of-00006.safetensors",
311
+ "model.layers.39.self_attn.q_proj.weight": "model-00006-of-00006.safetensors",
312
+ "model.layers.39.self_attn.v_proj.weight": "model-00006-of-00006.safetensors",
313
+ "model.layers.4.input_layernorm.weight": "model-00002-of-00006.safetensors",
314
+ "model.layers.4.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
315
+ "model.layers.4.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
316
+ "model.layers.4.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
317
+ "model.layers.4.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
318
+ "model.layers.4.self_attn.k_proj.weight": "model-00002-of-00006.safetensors",
319
+ "model.layers.4.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
320
+ "model.layers.4.self_attn.q_proj.weight": "model-00002-of-00006.safetensors",
321
+ "model.layers.4.self_attn.v_proj.weight": "model-00002-of-00006.safetensors",
322
+ "model.layers.5.input_layernorm.weight": "model-00002-of-00006.safetensors",
323
+ "model.layers.5.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
324
+ "model.layers.5.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
325
+ "model.layers.5.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
326
+ "model.layers.5.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
327
+ "model.layers.5.self_attn.k_proj.weight": "model-00002-of-00006.safetensors",
328
+ "model.layers.5.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
329
+ "model.layers.5.self_attn.q_proj.weight": "model-00002-of-00006.safetensors",
330
+ "model.layers.5.self_attn.v_proj.weight": "model-00002-of-00006.safetensors",
331
+ "model.layers.6.input_layernorm.weight": "model-00002-of-00006.safetensors",
332
+ "model.layers.6.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
333
+ "model.layers.6.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
334
+ "model.layers.6.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
335
+ "model.layers.6.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
336
+ "model.layers.6.self_attn.k_proj.weight": "model-00002-of-00006.safetensors",
337
+ "model.layers.6.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
338
+ "model.layers.6.self_attn.q_proj.weight": "model-00002-of-00006.safetensors",
339
+ "model.layers.6.self_attn.v_proj.weight": "model-00002-of-00006.safetensors",
340
+ "model.layers.7.input_layernorm.weight": "model-00002-of-00006.safetensors",
341
+ "model.layers.7.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
342
+ "model.layers.7.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
343
+ "model.layers.7.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
344
+ "model.layers.7.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
345
+ "model.layers.7.self_attn.k_proj.weight": "model-00002-of-00006.safetensors",
346
+ "model.layers.7.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
347
+ "model.layers.7.self_attn.q_proj.weight": "model-00002-of-00006.safetensors",
348
+ "model.layers.7.self_attn.v_proj.weight": "model-00002-of-00006.safetensors",
349
+ "model.layers.8.input_layernorm.weight": "model-00002-of-00006.safetensors",
350
+ "model.layers.8.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
351
+ "model.layers.8.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
352
+ "model.layers.8.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
353
+ "model.layers.8.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
354
+ "model.layers.8.self_attn.k_proj.weight": "model-00002-of-00006.safetensors",
355
+ "model.layers.8.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
356
+ "model.layers.8.self_attn.q_proj.weight": "model-00002-of-00006.safetensors",
357
+ "model.layers.8.self_attn.v_proj.weight": "model-00002-of-00006.safetensors",
358
+ "model.layers.9.input_layernorm.weight": "model-00002-of-00006.safetensors",
359
+ "model.layers.9.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
360
+ "model.layers.9.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
361
+ "model.layers.9.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
362
+ "model.layers.9.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
363
+ "model.layers.9.self_attn.k_proj.weight": "model-00002-of-00006.safetensors",
364
+ "model.layers.9.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
365
+ "model.layers.9.self_attn.q_proj.weight": "model-00002-of-00006.safetensors",
366
+ "model.layers.9.self_attn.v_proj.weight": "model-00002-of-00006.safetensors",
367
+ "model.norm.weight": "model-00006-of-00006.safetensors"
368
+ }
369
+ }
modeling_cerboai.py ADDED
@@ -0,0 +1,1702 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ # See the License for the specific language governing permissions and
12
+ # limitations under the License.
13
+ """ PyTorch CerboAI model."""
14
+ import math
15
+ import warnings
16
+ from typing import List, Optional, Tuple, Union, Dict
17
+
18
+ import torch
19
+ import torch.nn.functional as F
20
+ import torch.utils.checkpoint
21
+ from torch import nn
22
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
23
+
24
+ from transformers.activations import ACT2FN
25
+ from transformers.cache_utils import Cache, DynamicCache
26
+ from transformers.modeling_attn_mask_utils import (
27
+ AttentionMaskConverter,
28
+ _prepare_4d_attention_mask,
29
+ _prepare_4d_causal_attention_mask,
30
+ _prepare_4d_causal_attention_mask_for_sdpa,
31
+ )
32
+ from transformers.modeling_outputs import (
33
+ BaseModelOutputWithPast,
34
+ CausalLMOutputWithPast,
35
+ SequenceClassifierOutputWithPast,
36
+ )
37
+ from transformers.modeling_utils import PreTrainedModel
38
+ from transformers.pytorch_utils import (
39
+ ALL_LAYERNORM_LAYERS,
40
+ is_torch_greater_or_equal_than_1_13,
41
+ )
42
+ from transformers.utils import (
43
+ add_start_docstrings,
44
+ add_start_docstrings_to_model_forward,
45
+ is_flash_attn_2_available,
46
+ is_flash_attn_greater_or_equal_2_10,
47
+ logging,
48
+ replace_return_docstrings,
49
+ )
50
+ from transformers.utils.import_utils import is_torch_fx_available
51
+ from .configuration_cerboai import CerboAIConfig
52
+ import re
53
+
54
+ try:
55
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
56
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
57
+ except:
58
+ pass
59
+
60
+
61
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
62
+ # It means that the function will not be traced through and simply appear as a node in the graph.
63
+ if is_torch_fx_available():
64
+ if not is_torch_greater_or_equal_than_1_13:
65
+ import torch.fx
66
+
67
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
68
+
69
+
70
+ logger = logging.get_logger(__name__)
71
+
72
+ _CONFIG_FOR_DOC = "CerboAIConfig"
73
+
74
+
75
+ def _get_unpad_data(attention_mask):
76
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
77
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
78
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
79
+ cu_seqlens = F.pad(
80
+ torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)
81
+ )
82
+ return (
83
+ indices,
84
+ cu_seqlens,
85
+ max_seqlen_in_batch,
86
+ )
87
+
88
+
89
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
90
+ warnings.warn(
91
+ "Calling `transformers.models.cerboai.modeling_cerboai._prepare_4d_attention_mask` is deprecated and will be removed in v4.37. Use `transformers.modeling_attn_mask_utils._prepare_4d_attention_mask"
92
+ )
93
+ return _prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
94
+
95
+
96
+ def _make_causal_mask(
97
+ input_ids_shape: torch.Size,
98
+ dtype: torch.dtype,
99
+ device: torch.device,
100
+ past_key_values_length: int = 0,
101
+ ):
102
+ warnings.warn(
103
+ "Calling `transformers.models.cerboai.modeling_cerboai._make_causal_mask` is deprecated and will be removed in v4.37. Use `transformers.models.cerboai.modeling_cerboai.AttentionMaskConverter._make_causal_mask"
104
+ )
105
+ return AttentionMaskConverter._make_causal_mask(
106
+ input_ids_shape=input_ids_shape,
107
+ dtype=dtype,
108
+ device=device,
109
+ past_key_values_length=past_key_values_length,
110
+ )
111
+
112
+
113
+ # @torch.jit.script # type: ignore
114
+ def rms_layernorm(hidden: torch.Tensor, weight: torch.Tensor, eps: float):
115
+ old_dtype = hidden.dtype
116
+ variance = hidden.to(torch.float32).pow(2).mean(dim=-1, keepdim=True)
117
+ hidden = (hidden * torch.rsqrt(variance + eps)).to(old_dtype)
118
+ return hidden * weight
119
+
120
+
121
+ class CerboAIRMSNorm(nn.Module):
122
+ def __init__(self, hidden_size, eps=1e-6):
123
+ """
124
+ CerboAIRMSNorm is equivalent to T5LayerNorm
125
+ """
126
+ super().__init__()
127
+ self.weight = nn.Parameter(torch.ones(hidden_size))
128
+ self.variance_epsilon = eps
129
+
130
+ def forward(self, hidden_states):
131
+ return rms_layernorm(hidden_states, self.weight, self.variance_epsilon)
132
+
133
+
134
+ ALL_LAYERNORM_LAYERS.append(CerboAIRMSNorm)
135
+
136
+
137
+ class CerboAIRotaryEmbedding(nn.Module):
138
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
139
+ super().__init__()
140
+
141
+ self.dim = dim
142
+ self.max_position_embeddings = max_position_embeddings
143
+ self.base = base
144
+ inv_freq = 1.0 / (
145
+ self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
146
+ )
147
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
148
+
149
+ # Build here to make `torch.jit.trace` work.
150
+ self._set_cos_sin_cache(
151
+ # seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
152
+ seq_len=max_position_embeddings,
153
+ device=self.inv_freq.device,
154
+ dtype=torch.float32,
155
+ )
156
+
157
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
158
+ self.max_seq_len_cached = seq_len
159
+ t = torch.arange(
160
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
161
+ )
162
+ freqs = torch.outer(t, self.inv_freq)
163
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
164
+ emb = torch.cat((freqs, freqs), dim=-1)
165
+
166
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
167
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
168
+
169
+ def forward(self, x, seq_len=None):
170
+ # x: [bs, num_attention_heads, seq_len, head_size]
171
+ if seq_len > self.max_seq_len_cached:
172
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
173
+
174
+ return (
175
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
176
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
177
+ )
178
+
179
+
180
+ class CerboAILinearScalingRotaryEmbedding(CerboAIRotaryEmbedding):
181
+ """CerboAIRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
182
+
183
+ def __init__(
184
+ self,
185
+ dim,
186
+ max_position_embeddings=2048,
187
+ base=10000,
188
+ device=None,
189
+ scaling_factor=1.0,
190
+ ):
191
+ self.scaling_factor = scaling_factor
192
+ super().__init__(dim, max_position_embeddings, base, device)
193
+
194
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
195
+ self.max_seq_len_cached = seq_len
196
+ t = torch.arange(
197
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
198
+ )
199
+ t = t / self.scaling_factor
200
+
201
+ freqs = torch.outer(t, self.inv_freq)
202
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
203
+ emb = torch.cat((freqs, freqs), dim=-1)
204
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
205
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
206
+
207
+
208
+ class CerboAIDynamicNTKScalingRotaryEmbedding(CerboAIRotaryEmbedding):
209
+ """CerboAIRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
210
+
211
+ def __init__(
212
+ self,
213
+ dim,
214
+ max_position_embeddings=2048,
215
+ base=10000,
216
+ device=None,
217
+ scaling_factor=1.0,
218
+ ):
219
+ self.scaling_factor = scaling_factor
220
+ super().__init__(dim, max_position_embeddings, base, device)
221
+
222
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
223
+ self.max_seq_len_cached = seq_len
224
+
225
+ if seq_len > self.max_position_embeddings:
226
+ base = self.base * (
227
+ (self.scaling_factor * seq_len / self.max_position_embeddings)
228
+ - (self.scaling_factor - 1)
229
+ ) ** (self.dim / (self.dim - 2))
230
+ inv_freq = 1.0 / (
231
+ base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
232
+ )
233
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
234
+
235
+ t = torch.arange(
236
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
237
+ )
238
+
239
+ freqs = torch.outer(t, self.inv_freq)
240
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
241
+ emb = torch.cat((freqs, freqs), dim=-1)
242
+
243
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
244
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
245
+
246
+
247
+ def rotate_half(x):
248
+ """Rotates half the hidden dims of the input."""
249
+ x1 = x[..., : x.shape[-1] // 2]
250
+ x2 = x[..., x.shape[-1] // 2 :]
251
+ return torch.cat((-x2, x1), dim=-1)
252
+
253
+
254
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
255
+ """Applies Rotary Position Embedding to the query and key tensors.
256
+
257
+ Args:
258
+ q (`torch.Tensor`): The query tensor.
259
+ k (`torch.Tensor`): The key tensor.
260
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
261
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
262
+ position_ids (`torch.Tensor`):
263
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
264
+ used to pass offsetted position ids when working with a KV-cache.
265
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
266
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
267
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
268
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
269
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
270
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
271
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
272
+ Returns:
273
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
274
+ """
275
+ # cos = cos[position_ids].unsqueeze(unsqueeze_dim)
276
+ # sin = sin[position_ids].unsqueeze(unsqueeze_dim)
277
+ # q_embed = (q * cos) + (rotate_half(q) * sin)
278
+ # k_embed = (k * cos) + (rotate_half(k) * sin)
279
+ orig_dtype = k.dtype
280
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim) # [bs, 1, seq_len, dim]
281
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim) # [bs, 1, seq_len, dim]
282
+ q_fp32 = q.to(dtype=torch.float32, device=q.device)
283
+ k_fp32 = k.to(dtype=torch.float32, device=k.device)
284
+ q_embed = (q_fp32 * cos) + (rotate_half(q_fp32) * sin)
285
+ k_embed = (k_fp32 * cos) + (rotate_half(k_fp32) * sin)
286
+ return q_embed.to(dtype=orig_dtype), k_embed.to(dtype=orig_dtype)
287
+
288
+
289
+ class CerboAIMLP(nn.Module):
290
+ def __init__(self, config):
291
+ super().__init__()
292
+ self.config = config
293
+ self.hidden_size = config.hidden_size
294
+ self.intermediate_size = config.intermediate_size
295
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
296
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
297
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
298
+ self.act_fn = ACT2FN[config.hidden_act]
299
+
300
+ def forward(self, x):
301
+ if self.config.pretraining_tp > 1:
302
+ slice = self.intermediate_size // self.config.pretraining_tp
303
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
304
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
305
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
306
+
307
+ gate_proj = torch.cat(
308
+ [
309
+ F.linear(x, gate_proj_slices[i])
310
+ for i in range(self.config.pretraining_tp)
311
+ ],
312
+ dim=-1,
313
+ )
314
+ up_proj = torch.cat(
315
+ [
316
+ F.linear(x, up_proj_slices[i])
317
+ for i in range(self.config.pretraining_tp)
318
+ ],
319
+ dim=-1,
320
+ )
321
+
322
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
323
+ down_proj = [
324
+ F.linear(intermediate_states[i], down_proj_slices[i])
325
+ for i in range(self.config.pretraining_tp)
326
+ ]
327
+ down_proj = sum(down_proj)
328
+ else:
329
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
330
+
331
+ return down_proj
332
+
333
+
334
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
335
+ """
336
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
337
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
338
+ """
339
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
340
+ if n_rep == 1:
341
+ return hidden_states
342
+ hidden_states = hidden_states[:, :, None, :, :].expand(
343
+ batch, num_key_value_heads, n_rep, slen, head_dim
344
+ )
345
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
346
+
347
+
348
+ class CerboAIAttention(nn.Module):
349
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
350
+
351
+ def __init__(self, config: CerboAIConfig, layer_idx: Optional[int] = None):
352
+ super().__init__()
353
+ self.config = config
354
+ self.layer_idx = layer_idx
355
+ if layer_idx is None:
356
+ logger.warning_once(
357
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
358
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
359
+ "when creating this class."
360
+ )
361
+
362
+ self.attention_dropout = config.attention_dropout
363
+ self.hidden_size = config.hidden_size
364
+ self.num_heads = config.num_attention_heads
365
+ self.head_dim = self.hidden_size // self.num_heads
366
+ self.num_key_value_heads = config.num_key_value_heads
367
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
368
+ self.max_position_embeddings = config.max_position_embeddings
369
+ self.rope_theta = config.rope_theta
370
+ self.is_causal = True
371
+
372
+ if (self.head_dim * self.num_heads) != self.hidden_size:
373
+ raise ValueError(
374
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
375
+ f" and `num_heads`: {self.num_heads})."
376
+ )
377
+
378
+ self.q_proj = nn.Linear(
379
+ self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias
380
+ )
381
+ self.k_proj = nn.Linear(
382
+ self.hidden_size,
383
+ self.num_key_value_heads * self.head_dim,
384
+ bias=config.attention_bias,
385
+ )
386
+ self.v_proj = nn.Linear(
387
+ self.hidden_size,
388
+ self.num_key_value_heads * self.head_dim,
389
+ bias=config.attention_bias,
390
+ )
391
+ self.o_proj = nn.Linear(
392
+ self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias
393
+ )
394
+ self._init_rope()
395
+
396
+ def _init_rope(self):
397
+ if self.config.rope_scaling is None:
398
+ self.rotary_emb = CerboAIRotaryEmbedding(
399
+ self.head_dim,
400
+ max_position_embeddings=self.max_position_embeddings,
401
+ base=self.rope_theta,
402
+ )
403
+ else:
404
+ scaling_type = self.config.rope_scaling["type"]
405
+ scaling_factor = self.config.rope_scaling["factor"]
406
+ if scaling_type == "linear":
407
+ self.rotary_emb = CerboAILinearScalingRotaryEmbedding(
408
+ self.head_dim,
409
+ max_position_embeddings=self.max_position_embeddings,
410
+ scaling_factor=scaling_factor,
411
+ base=self.rope_theta,
412
+ )
413
+ elif scaling_type == "dynamic":
414
+ self.rotary_emb = CerboAIDynamicNTKScalingRotaryEmbedding(
415
+ self.head_dim,
416
+ max_position_embeddings=self.max_position_embeddings,
417
+ scaling_factor=scaling_factor,
418
+ base=self.rope_theta,
419
+ )
420
+ else:
421
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
422
+
423
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
424
+ return (
425
+ tensor.view(bsz, seq_len, self.num_heads, self.head_dim)
426
+ .transpose(1, 2)
427
+ .contiguous()
428
+ )
429
+
430
+ def forward(
431
+ self,
432
+ hidden_states: torch.Tensor,
433
+ attention_mask: Optional[torch.Tensor] = None,
434
+ position_ids: Optional[torch.LongTensor] = None,
435
+ past_key_value: Optional[Cache] = None,
436
+ output_attentions: bool = False,
437
+ use_cache: bool = False,
438
+ **kwargs,
439
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
440
+ if "padding_mask" in kwargs:
441
+ warnings.warn(
442
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
443
+ )
444
+
445
+ bsz, q_len, _ = hidden_states.size()
446
+
447
+ if self.config.pretraining_tp > 1:
448
+ key_value_slicing = (
449
+ self.num_key_value_heads * self.head_dim
450
+ ) // self.config.pretraining_tp
451
+ query_slices = self.q_proj.weight.split(
452
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
453
+ )
454
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
455
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
456
+
457
+ query_states = [
458
+ F.linear(hidden_states, query_slices[i])
459
+ for i in range(self.config.pretraining_tp)
460
+ ]
461
+ query_states = torch.cat(query_states, dim=-1)
462
+
463
+ key_states = [
464
+ F.linear(hidden_states, key_slices[i])
465
+ for i in range(self.config.pretraining_tp)
466
+ ]
467
+ key_states = torch.cat(key_states, dim=-1)
468
+
469
+ value_states = [
470
+ F.linear(hidden_states, value_slices[i])
471
+ for i in range(self.config.pretraining_tp)
472
+ ]
473
+ value_states = torch.cat(value_states, dim=-1)
474
+
475
+ else:
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
+ query_states = query_states.view(
481
+ bsz, q_len, self.num_heads, self.head_dim
482
+ ).transpose(1, 2)
483
+ key_states = key_states.view(
484
+ bsz, q_len, self.num_key_value_heads, self.head_dim
485
+ ).transpose(1, 2)
486
+ value_states = value_states.view(
487
+ bsz, q_len, self.num_key_value_heads, self.head_dim
488
+ ).transpose(1, 2)
489
+
490
+ kv_seq_len = key_states.shape[-2]
491
+ if past_key_value is not None:
492
+ if self.layer_idx is None:
493
+ raise ValueError(
494
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
495
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
496
+ "with a layer index."
497
+ )
498
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
499
+ cos, sin = self.rotary_emb(value_states.to(torch.float32), seq_len=kv_seq_len)
500
+
501
+ query_states, key_states = apply_rotary_pos_emb(
502
+ query_states, key_states, cos, sin, position_ids
503
+ )
504
+
505
+ if past_key_value is not None:
506
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
507
+ key_states, value_states = past_key_value.update(
508
+ key_states, value_states, self.layer_idx, cache_kwargs
509
+ )
510
+
511
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
512
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
513
+
514
+ attn_weights = torch.matmul(
515
+ query_states, key_states.transpose(2, 3)
516
+ ) / math.sqrt(self.head_dim)
517
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
518
+ raise ValueError(
519
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
520
+ f" {attn_weights.size()}"
521
+ )
522
+
523
+ if attention_mask is not None:
524
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
525
+ raise ValueError(
526
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
527
+ )
528
+ attn_weights = attn_weights + attention_mask
529
+
530
+ # upcast attention to fp32
531
+ attn_weights = nn.functional.softmax(
532
+ attn_weights, dim=-1, dtype=torch.float32
533
+ ).to(query_states.dtype)
534
+ attn_weights = nn.functional.dropout(
535
+ attn_weights, p=self.attention_dropout, training=self.training
536
+ )
537
+ attn_output = torch.matmul(attn_weights, value_states)
538
+
539
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
540
+ raise ValueError(
541
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
542
+ f" {attn_output.size()}"
543
+ )
544
+
545
+ attn_output = attn_output.transpose(1, 2).contiguous()
546
+
547
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
548
+
549
+ if self.config.pretraining_tp > 1:
550
+ attn_output = attn_output.split(
551
+ self.hidden_size // self.config.pretraining_tp, dim=2
552
+ )
553
+ o_proj_slices = self.o_proj.weight.split(
554
+ self.hidden_size // self.config.pretraining_tp, dim=1
555
+ )
556
+ attn_output = sum(
557
+ [
558
+ F.linear(attn_output[i], o_proj_slices[i])
559
+ for i in range(self.config.pretraining_tp)
560
+ ]
561
+ )
562
+ else:
563
+ attn_output = self.o_proj(attn_output)
564
+
565
+ if not output_attentions:
566
+ attn_weights = None
567
+
568
+ return attn_output, attn_weights, past_key_value
569
+
570
+
571
+ class CerboAIFlashAttention2(CerboAIAttention):
572
+ """
573
+ CerboAI flash attention module. This module inherits from `CerboAIAttention` as the weights of the module stays
574
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
575
+ flash attention and deal with padding tokens in case the input contains any of them.
576
+ """
577
+
578
+ def __init__(self, *args, **kwargs):
579
+ super().__init__(*args, **kwargs)
580
+
581
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
582
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
583
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
584
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
585
+
586
+ def forward(
587
+ self,
588
+ hidden_states: torch.Tensor,
589
+ attention_mask: Optional[torch.LongTensor] = None,
590
+ position_ids: Optional[torch.LongTensor] = None,
591
+ past_key_value: Optional[Cache] = None,
592
+ output_attentions: bool = False,
593
+ use_cache: bool = False,
594
+ **kwargs,
595
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
596
+ # CerboAIFlashAttention2 attention does not support output_attentions
597
+ if "padding_mask" in kwargs:
598
+ warnings.warn(
599
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
600
+ )
601
+
602
+ # overwrite attention_mask with padding_mask
603
+ attention_mask = kwargs.pop("padding_mask")
604
+
605
+ output_attentions = False
606
+
607
+ bsz, q_len, _ = hidden_states.size()
608
+
609
+ query_states = self.q_proj(hidden_states)
610
+ key_states = self.k_proj(hidden_states)
611
+ value_states = self.v_proj(hidden_states)
612
+
613
+ # Flash attention requires the input to have the shape
614
+ # batch_size x seq_length x head_dim x hidden_dim
615
+ # therefore we just need to keep the original shape
616
+ query_states = query_states.view(
617
+ bsz, q_len, self.num_heads, self.head_dim
618
+ ).transpose(1, 2)
619
+ key_states = key_states.view(
620
+ bsz, q_len, self.num_key_value_heads, self.head_dim
621
+ ).transpose(1, 2)
622
+ value_states = value_states.view(
623
+ bsz, q_len, self.num_key_value_heads, self.head_dim
624
+ ).transpose(1, 2)
625
+
626
+ kv_seq_len = key_states.shape[-2]
627
+ if past_key_value is not None:
628
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
629
+ cos, sin = self.rotary_emb(value_states.to(torch.float32), seq_len=kv_seq_len)
630
+ query_states, key_states = apply_rotary_pos_emb(
631
+ query_states, key_states, cos, sin, position_ids
632
+ )
633
+
634
+ if past_key_value is not None:
635
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
636
+ key_states, value_states = past_key_value.update(
637
+ key_states, value_states, self.layer_idx, cache_kwargs
638
+ )
639
+
640
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
641
+ # to be able to avoid many of these transpose/reshape/view.
642
+ query_states = query_states.transpose(1, 2)
643
+ key_states = key_states.transpose(1, 2)
644
+ value_states = value_states.transpose(1, 2)
645
+
646
+ dropout_rate = self.attention_dropout if self.training else 0.0
647
+
648
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
649
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
650
+ # cast them back in the correct dtype just to be sure everything works as expected.
651
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
652
+ # in fp32. (CerboAIRMSNorm handles it correctly)
653
+
654
+ input_dtype = query_states.dtype
655
+ if input_dtype == torch.float32:
656
+ # Handle the case where the model is quantized
657
+ if hasattr(self.config, "_pre_quantization_dtype"):
658
+ target_dtype = self.config._pre_quantization_dtype
659
+ else:
660
+ target_dtype = self.q_proj.weight.dtype
661
+
662
+ logger.warning_once(
663
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
664
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
665
+ f" {target_dtype}."
666
+ )
667
+
668
+ query_states = query_states.to(target_dtype)
669
+ key_states = key_states.to(target_dtype)
670
+ value_states = value_states.to(target_dtype)
671
+
672
+ attn_output = self._flash_attention_forward(
673
+ query_states,
674
+ key_states,
675
+ value_states,
676
+ attention_mask,
677
+ q_len,
678
+ dropout=dropout_rate,
679
+ )
680
+
681
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
682
+ attn_output = self.o_proj(attn_output)
683
+
684
+ if not output_attentions:
685
+ attn_weights = None
686
+
687
+ return attn_output, attn_weights, past_key_value
688
+
689
+ def _flash_attention_forward(
690
+ self,
691
+ query_states,
692
+ key_states,
693
+ value_states,
694
+ attention_mask,
695
+ query_length,
696
+ dropout=0.0,
697
+ softmax_scale=None,
698
+ ):
699
+ """
700
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
701
+ first unpad the input, then computes the attention scores and pad the final attention scores.
702
+
703
+ Args:
704
+ query_states (`torch.Tensor`):
705
+ Input query states to be passed to Flash Attention API
706
+ key_states (`torch.Tensor`):
707
+ Input key states to be passed to Flash Attention API
708
+ value_states (`torch.Tensor`):
709
+ Input value states to be passed to Flash Attention API
710
+ attention_mask (`torch.Tensor`):
711
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
712
+ position of padding tokens and 1 for the position of non-padding tokens.
713
+ dropout (`int`, *optional*):
714
+ Attention dropout
715
+ softmax_scale (`float`, *optional*):
716
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
717
+ """
718
+ if not self._flash_attn_uses_top_left_mask:
719
+ causal = self.is_causal
720
+ else:
721
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in CerboAIFlashAttention2 __init__.
722
+ causal = self.is_causal and query_length != 1
723
+ # Contains at least one padding token in the sequence
724
+ if attention_mask is not None:
725
+ batch_size = query_states.shape[0]
726
+ (
727
+ query_states,
728
+ key_states,
729
+ value_states,
730
+ indices_q,
731
+ cu_seq_lens,
732
+ max_seq_lens,
733
+ ) = self._upad_input(
734
+ query_states, key_states, value_states, attention_mask, query_length
735
+ )
736
+
737
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
738
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
739
+ attn_output_unpad = flash_attn_varlen_func(
740
+ query_states,
741
+ key_states,
742
+ value_states,
743
+ cu_seqlens_q=cu_seqlens_q,
744
+ cu_seqlens_k=cu_seqlens_k,
745
+ max_seqlen_q=max_seqlen_in_batch_q,
746
+ max_seqlen_k=max_seqlen_in_batch_k,
747
+ dropout_p=dropout,
748
+ softmax_scale=softmax_scale,
749
+ causal=causal,
750
+ )
751
+
752
+ attn_output = pad_input(
753
+ attn_output_unpad, indices_q, batch_size, query_length
754
+ )
755
+ else:
756
+ attn_output = flash_attn_func(
757
+ query_states,
758
+ key_states,
759
+ value_states,
760
+ dropout,
761
+ softmax_scale=softmax_scale,
762
+ causal=causal,
763
+ )
764
+
765
+ return attn_output
766
+
767
+ def _upad_input(
768
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
769
+ ):
770
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
771
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
772
+
773
+ key_layer = index_first_axis(
774
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
775
+ indices_k,
776
+ )
777
+ value_layer = index_first_axis(
778
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
779
+ indices_k,
780
+ )
781
+ if query_length == kv_seq_len:
782
+ query_layer = index_first_axis(
783
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
784
+ indices_k,
785
+ )
786
+ cu_seqlens_q = cu_seqlens_k
787
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
788
+ indices_q = indices_k
789
+ elif query_length == 1:
790
+ max_seqlen_in_batch_q = 1
791
+ cu_seqlens_q = torch.arange(
792
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
793
+ ) # There is a memcpy here, that is very bad.
794
+ indices_q = cu_seqlens_q[:-1]
795
+ query_layer = query_layer.squeeze(1)
796
+ else:
797
+ # The -q_len: slice assumes left padding.
798
+ attention_mask = attention_mask[:, -query_length:]
799
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
800
+ query_layer, attention_mask
801
+ )
802
+
803
+ return (
804
+ query_layer,
805
+ key_layer,
806
+ value_layer,
807
+ indices_q,
808
+ (cu_seqlens_q, cu_seqlens_k),
809
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
810
+ )
811
+
812
+
813
+ class CerboAISdpaAttention(CerboAIAttention):
814
+ """
815
+ CerboAI attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
816
+ `CerboAIAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
817
+ SDPA API.
818
+ """
819
+
820
+ # Adapted from CerboAIAttention.forward
821
+ def forward(
822
+ self,
823
+ hidden_states: torch.Tensor,
824
+ attention_mask: Optional[torch.Tensor] = None,
825
+ position_ids: Optional[torch.LongTensor] = None,
826
+ past_key_value: Optional[Cache] = None,
827
+ output_attentions: bool = False,
828
+ use_cache: bool = False,
829
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
830
+ if output_attentions:
831
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
832
+ logger.warning_once(
833
+ "CerboAIModel is using CerboAISdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
834
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
835
+ )
836
+ return super().forward(
837
+ hidden_states=hidden_states,
838
+ attention_mask=attention_mask,
839
+ position_ids=position_ids,
840
+ past_key_value=past_key_value,
841
+ output_attentions=output_attentions,
842
+ use_cache=use_cache,
843
+ )
844
+
845
+ bsz, q_len, _ = hidden_states.size()
846
+
847
+ query_states = self.q_proj(hidden_states)
848
+ key_states = self.k_proj(hidden_states)
849
+ value_states = self.v_proj(hidden_states)
850
+
851
+ query_states = query_states.view(
852
+ bsz, q_len, self.num_heads, self.head_dim
853
+ ).transpose(1, 2)
854
+ key_states = key_states.view(
855
+ bsz, q_len, self.num_key_value_heads, self.head_dim
856
+ ).transpose(1, 2)
857
+ value_states = value_states.view(
858
+ bsz, q_len, self.num_key_value_heads, self.head_dim
859
+ ).transpose(1, 2)
860
+
861
+ kv_seq_len = key_states.shape[-2]
862
+ if past_key_value is not None:
863
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
864
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
865
+
866
+ query_states, key_states = apply_rotary_pos_emb(
867
+ query_states, key_states, cos, sin, position_ids
868
+ )
869
+
870
+ if past_key_value is not None:
871
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
872
+ key_states, value_states = past_key_value.update(
873
+ key_states, value_states, self.layer_idx, cache_kwargs
874
+ )
875
+
876
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
877
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
878
+
879
+ if attention_mask is not None:
880
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
881
+ raise ValueError(
882
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
883
+ )
884
+
885
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
886
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
887
+ if query_states.device.type == "cuda" and attention_mask is not None:
888
+ query_states = query_states.contiguous()
889
+ key_states = key_states.contiguous()
890
+ value_states = value_states.contiguous()
891
+
892
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
893
+ query_states,
894
+ key_states,
895
+ value_states,
896
+ attn_mask=attention_mask,
897
+ dropout_p=self.attention_dropout if self.training else 0.0,
898
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
899
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
900
+ )
901
+
902
+ attn_output = attn_output.transpose(1, 2).contiguous()
903
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
904
+
905
+ attn_output = self.o_proj(attn_output)
906
+
907
+ return attn_output, None, past_key_value
908
+
909
+
910
+ CerboAI_ATTENTION_CLASSES = {
911
+ "eager": CerboAIAttention,
912
+ "flash_attention_2": CerboAIFlashAttention2,
913
+ "sdpa": CerboAISdpaAttention,
914
+ }
915
+
916
+
917
+ class CerboAIDecoderLayer(nn.Module):
918
+ def __init__(self, config: CerboAIConfig, layer_idx: int):
919
+ super().__init__()
920
+ self.hidden_size = config.hidden_size
921
+ self.self_attn = CerboAI_ATTENTION_CLASSES[config._attn_implementation](
922
+ config=config, layer_idx=layer_idx
923
+ )
924
+
925
+ self.mlp = CerboAIMLP(config)
926
+ self.input_layernorm = CerboAIRMSNorm(
927
+ config.hidden_size, eps=config.rms_norm_eps
928
+ )
929
+ self.post_attention_layernorm = CerboAIRMSNorm(
930
+ config.hidden_size, eps=config.rms_norm_eps
931
+ )
932
+
933
+ self.scale_depth = config.scale_depth
934
+ self.num_hidden_layers = config.num_hidden_layers
935
+
936
+ def forward(
937
+ self,
938
+ hidden_states: torch.Tensor,
939
+ attention_mask: Optional[torch.Tensor] = None,
940
+ position_ids: Optional[torch.LongTensor] = None,
941
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
942
+ output_attentions: Optional[bool] = False,
943
+ use_cache: Optional[bool] = False,
944
+ **kwargs,
945
+ ) -> Tuple[
946
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
947
+ ]:
948
+ """
949
+ Args:
950
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
951
+ attention_mask (`torch.FloatTensor`, *optional*):
952
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
953
+ query_sequence_length, key_sequence_length)` if default attention is used.
954
+ output_attentions (`bool`, *optional*):
955
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
956
+ returned tensors for more detail.
957
+ use_cache (`bool`, *optional*):
958
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
959
+ (see `past_key_values`).
960
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
961
+ """
962
+ if "padding_mask" in kwargs:
963
+ warnings.warn(
964
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
965
+ )
966
+
967
+ residual = hidden_states
968
+ hidden_states = self.input_layernorm(hidden_states)
969
+ # Self Attention
970
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
971
+ hidden_states=hidden_states,
972
+ attention_mask=attention_mask,
973
+ position_ids=position_ids,
974
+ past_key_value=past_key_value,
975
+ output_attentions=output_attentions,
976
+ use_cache=use_cache,
977
+ **kwargs,
978
+ )
979
+
980
+ hidden_states = residual + hidden_states * (
981
+ self.scale_depth / math.sqrt(self.num_hidden_layers)
982
+ )
983
+
984
+ # Fully Connected
985
+ residual = hidden_states
986
+ hidden_states = self.post_attention_layernorm(hidden_states)
987
+
988
+ hidden_states = self.mlp(hidden_states)
989
+ hidden_states = residual + hidden_states * (
990
+ self.scale_depth / math.sqrt(self.num_hidden_layers)
991
+ )
992
+
993
+ outputs = (hidden_states,)
994
+
995
+ if output_attentions:
996
+ outputs += (self_attn_weights,)
997
+
998
+ if use_cache:
999
+ outputs += (present_key_value,)
1000
+
1001
+ return outputs
1002
+
1003
+
1004
+ CerboAI_START_DOCSTRING = r"""
1005
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1006
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1007
+ etc.)
1008
+
1009
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1010
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1011
+ and behavior.
1012
+
1013
+ Parameters:
1014
+ config ([`CerboAIConfig`]):
1015
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1016
+ load the weights associated with the model, only the configuration. Check out the
1017
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1018
+ """
1019
+
1020
+
1021
+ @add_start_docstrings(
1022
+ "The bare CerboAI Model outputting raw hidden-states without any specific head on top.",
1023
+ CerboAI_START_DOCSTRING,
1024
+ )
1025
+ class CerboAIPreTrainedModel(PreTrainedModel):
1026
+ config_class = CerboAIConfig
1027
+ base_model_prefix = "model"
1028
+ supports_gradient_checkpointing = True
1029
+ _no_split_modules = ["CerboAIDecoderLayer"]
1030
+ _skip_keys_device_placement = "past_key_values"
1031
+ _supports_flash_attn_2 = True
1032
+ _supports_sdpa = True
1033
+ _supports_cache_class = True
1034
+
1035
+ def _init_weights(self, module):
1036
+ std = self.config.initializer_range
1037
+ if isinstance(module, nn.Linear):
1038
+ module.weight.data.normal_(mean=0.0, std=std)
1039
+ if module.bias is not None:
1040
+ module.bias.data.zero_()
1041
+ elif isinstance(module, nn.Embedding):
1042
+ module.weight.data.normal_(mean=0.0, std=std)
1043
+ if module.padding_idx is not None:
1044
+ module.weight.data[module.padding_idx].zero_()
1045
+
1046
+
1047
+ CerboAI_INPUTS_DOCSTRING = r"""
1048
+ Args:
1049
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1050
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1051
+ it.
1052
+
1053
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1054
+ [`PreTrainedTokenizer.__call__`] for details.
1055
+
1056
+ [What are input IDs?](../glossary#input-ids)
1057
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1058
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1059
+
1060
+ - 1 for tokens that are **not masked**,
1061
+ - 0 for tokens that are **masked**.
1062
+
1063
+ [What are attention masks?](../glossary#attention-mask)
1064
+
1065
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1066
+ [`PreTrainedTokenizer.__call__`] for details.
1067
+
1068
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1069
+ `past_key_values`).
1070
+
1071
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1072
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1073
+ information on the default strategy.
1074
+
1075
+ - 1 indicates the head is **not masked**,
1076
+ - 0 indicates the head is **masked**.
1077
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1078
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1079
+ config.n_positions - 1]`.
1080
+
1081
+ [What are position IDs?](../glossary#position-ids)
1082
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1083
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1084
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1085
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1086
+
1087
+ Two formats are allowed:
1088
+ - a [`~cache_utils.Cache`] instance;
1089
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1090
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1091
+ cache format.
1092
+
1093
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1094
+ legacy cache format will be returned.
1095
+
1096
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1097
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1098
+ of shape `(batch_size, sequence_length)`.
1099
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1100
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1101
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1102
+ model's internal embedding lookup matrix.
1103
+ use_cache (`bool`, *optional*):
1104
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1105
+ `past_key_values`).
1106
+ output_attentions (`bool`, *optional*):
1107
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1108
+ tensors for more detail.
1109
+ output_hidden_states (`bool`, *optional*):
1110
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1111
+ more detail.
1112
+ return_dict (`bool`, *optional*):
1113
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1114
+ """
1115
+
1116
+
1117
+ @add_start_docstrings(
1118
+ "The bare CerboAI Model outputting raw hidden-states without any specific head on top.",
1119
+ CerboAI_START_DOCSTRING,
1120
+ )
1121
+ class CerboAIModel(CerboAIPreTrainedModel):
1122
+ """
1123
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`CerboAIDecoderLayer`]
1124
+
1125
+ Args:
1126
+ config: CerboAIConfig
1127
+ """
1128
+
1129
+ def __init__(self, config: CerboAIConfig):
1130
+ super().__init__(config)
1131
+ self.padding_idx = config.pad_token_id
1132
+ self.vocab_size = config.vocab_size
1133
+
1134
+ self.embed_tokens = nn.Embedding(
1135
+ config.vocab_size, config.hidden_size, self.padding_idx
1136
+ )
1137
+ self.layers = nn.ModuleList(
1138
+ [
1139
+ CerboAIDecoderLayer(config, layer_idx)
1140
+ for layer_idx in range(config.num_hidden_layers)
1141
+ ]
1142
+ )
1143
+ self._use_sdpa = config._attn_implementation == "sdpa"
1144
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1145
+
1146
+ self.norm = CerboAIRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1147
+
1148
+ self.gradient_checkpointing = False
1149
+ # Initialize weights and apply final processing
1150
+ self.post_init()
1151
+
1152
+ def get_input_embeddings(self):
1153
+ return self.embed_tokens
1154
+
1155
+ def set_input_embeddings(self, value):
1156
+ self.embed_tokens = value
1157
+
1158
+ @add_start_docstrings_to_model_forward(CerboAI_INPUTS_DOCSTRING)
1159
+ def forward(
1160
+ self,
1161
+ input_ids: torch.LongTensor = None,
1162
+ attention_mask: Optional[torch.Tensor] = None,
1163
+ position_ids: Optional[torch.LongTensor] = None,
1164
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1165
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1166
+ use_cache: Optional[bool] = None,
1167
+ output_attentions: Optional[bool] = None,
1168
+ output_hidden_states: Optional[bool] = None,
1169
+ return_dict: Optional[bool] = None,
1170
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1171
+ output_attentions = (
1172
+ output_attentions
1173
+ if output_attentions is not None
1174
+ else self.config.output_attentions
1175
+ )
1176
+ output_hidden_states = (
1177
+ output_hidden_states
1178
+ if output_hidden_states is not None
1179
+ else self.config.output_hidden_states
1180
+ )
1181
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1182
+
1183
+ return_dict = (
1184
+ return_dict if return_dict is not None else self.config.use_return_dict
1185
+ )
1186
+
1187
+ # retrieve input_ids and inputs_embeds
1188
+ if input_ids is not None and inputs_embeds is not None:
1189
+ raise ValueError(
1190
+ "You cannot specify both input_ids and inputs_embeds at the same time"
1191
+ )
1192
+ elif input_ids is not None:
1193
+ batch_size, seq_length = input_ids.shape[:2]
1194
+ elif inputs_embeds is not None:
1195
+ batch_size, seq_length = inputs_embeds.shape[:2]
1196
+ else:
1197
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1198
+
1199
+ if self.gradient_checkpointing and self.training:
1200
+ if use_cache:
1201
+ logger.warning_once(
1202
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1203
+ )
1204
+ use_cache = False
1205
+
1206
+ past_key_values_length = 0
1207
+ if use_cache:
1208
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1209
+ if use_legacy_cache:
1210
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1211
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1212
+
1213
+ if position_ids is None:
1214
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1215
+ position_ids = torch.arange(
1216
+ past_key_values_length,
1217
+ seq_length + past_key_values_length,
1218
+ dtype=torch.long,
1219
+ device=device,
1220
+ )
1221
+ position_ids = position_ids.unsqueeze(0)
1222
+
1223
+ if inputs_embeds is None:
1224
+ inputs_embeds = self.embed_tokens(input_ids) * self.config.scale_emb
1225
+
1226
+ if self._use_flash_attention_2:
1227
+ # 2d mask is passed through the layers
1228
+ attention_mask = (
1229
+ attention_mask
1230
+ if (attention_mask is not None and 0 in attention_mask)
1231
+ else None
1232
+ )
1233
+ elif self._use_sdpa and not output_attentions:
1234
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1235
+ # the manual implementation that requires a 4D causal mask in all cases.
1236
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1237
+ attention_mask,
1238
+ (batch_size, seq_length),
1239
+ inputs_embeds,
1240
+ past_key_values_length,
1241
+ )
1242
+ else:
1243
+ # 4d mask is passed through the layers
1244
+ attention_mask = _prepare_4d_causal_attention_mask(
1245
+ attention_mask,
1246
+ (batch_size, seq_length),
1247
+ inputs_embeds,
1248
+ past_key_values_length,
1249
+ )
1250
+
1251
+ # embed positions
1252
+ hidden_states = inputs_embeds
1253
+
1254
+ # decoder layers
1255
+ all_hidden_states = () if output_hidden_states else None
1256
+ all_self_attns = () if output_attentions else None
1257
+ next_decoder_cache = None
1258
+
1259
+ for decoder_layer in self.layers:
1260
+ if output_hidden_states:
1261
+ all_hidden_states += (hidden_states,)
1262
+
1263
+ if self.gradient_checkpointing and self.training:
1264
+ layer_outputs = self._gradient_checkpointing_func(
1265
+ decoder_layer.__call__,
1266
+ hidden_states,
1267
+ attention_mask,
1268
+ position_ids,
1269
+ past_key_values,
1270
+ output_attentions,
1271
+ use_cache,
1272
+ )
1273
+ else:
1274
+ layer_outputs = decoder_layer(
1275
+ hidden_states,
1276
+ attention_mask=attention_mask,
1277
+ position_ids=position_ids,
1278
+ past_key_value=past_key_values,
1279
+ output_attentions=output_attentions,
1280
+ use_cache=use_cache,
1281
+ )
1282
+
1283
+ hidden_states = layer_outputs[0]
1284
+
1285
+ if use_cache:
1286
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1287
+
1288
+ if output_attentions:
1289
+ all_self_attns += (layer_outputs[1],)
1290
+
1291
+ hidden_states = self.norm(hidden_states)
1292
+
1293
+ # add hidden states from the last decoder layer
1294
+ if output_hidden_states:
1295
+ all_hidden_states += (hidden_states,)
1296
+
1297
+ next_cache = None
1298
+ if use_cache:
1299
+ next_cache = (
1300
+ next_decoder_cache.to_legacy_cache()
1301
+ if use_legacy_cache
1302
+ else next_decoder_cache
1303
+ )
1304
+ if not return_dict:
1305
+ return tuple(
1306
+ v
1307
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
1308
+ if v is not None
1309
+ )
1310
+ return BaseModelOutputWithPast(
1311
+ last_hidden_state=hidden_states,
1312
+ past_key_values=next_cache,
1313
+ hidden_states=all_hidden_states,
1314
+ attentions=all_self_attns,
1315
+ )
1316
+
1317
+
1318
+ class CerboAIForCausalLM(CerboAIPreTrainedModel):
1319
+ _tied_weights_keys = ["lm_head.weight"]
1320
+
1321
+ def __init__(self, config):
1322
+ super().__init__(config)
1323
+ self.model = CerboAIModel(config)
1324
+ self.vocab_size = config.vocab_size
1325
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1326
+
1327
+ # Initialize weights and apply final processing
1328
+ self.post_init()
1329
+
1330
+ def get_input_embeddings(self):
1331
+ return self.model.embed_tokens
1332
+
1333
+ def set_input_embeddings(self, value):
1334
+ self.model.embed_tokens = value
1335
+
1336
+ def get_output_embeddings(self):
1337
+ return self.lm_head
1338
+
1339
+ def set_output_embeddings(self, new_embeddings):
1340
+ self.lm_head = new_embeddings
1341
+
1342
+ def set_decoder(self, decoder):
1343
+ self.model = decoder
1344
+
1345
+ def get_decoder(self):
1346
+ return self.model
1347
+
1348
+ @add_start_docstrings_to_model_forward(CerboAI_INPUTS_DOCSTRING)
1349
+ @replace_return_docstrings(
1350
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
1351
+ )
1352
+ def forward(
1353
+ self,
1354
+ input_ids: torch.LongTensor = None,
1355
+ attention_mask: Optional[torch.Tensor] = None,
1356
+ position_ids: Optional[torch.LongTensor] = None,
1357
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1358
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1359
+ labels: Optional[torch.LongTensor] = None,
1360
+ use_cache: Optional[bool] = None,
1361
+ output_attentions: Optional[bool] = None,
1362
+ output_hidden_states: Optional[bool] = None,
1363
+ return_dict: Optional[bool] = None,
1364
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1365
+ r"""
1366
+ Args:
1367
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1368
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1369
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1370
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1371
+
1372
+ Returns:
1373
+
1374
+ ```"""
1375
+ output_attentions = (
1376
+ output_attentions
1377
+ if output_attentions is not None
1378
+ else self.config.output_attentions
1379
+ )
1380
+ output_hidden_states = (
1381
+ output_hidden_states
1382
+ if output_hidden_states is not None
1383
+ else self.config.output_hidden_states
1384
+ )
1385
+ return_dict = (
1386
+ return_dict if return_dict is not None else self.config.use_return_dict
1387
+ )
1388
+
1389
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1390
+ outputs = self.model(
1391
+ input_ids=input_ids,
1392
+ attention_mask=attention_mask,
1393
+ position_ids=position_ids,
1394
+ past_key_values=past_key_values,
1395
+ inputs_embeds=inputs_embeds,
1396
+ use_cache=use_cache,
1397
+ output_attentions=output_attentions,
1398
+ output_hidden_states=output_hidden_states,
1399
+ return_dict=return_dict,
1400
+ )
1401
+
1402
+ hidden_states = outputs[0]
1403
+ if self.config.pretraining_tp > 1:
1404
+ lm_head_slices = self.lm_head.weight.split(
1405
+ self.vocab_size // self.config.pretraining_tp, dim=0
1406
+ )
1407
+ logits = [
1408
+ F.linear(hidden_states, lm_head_slices[i])
1409
+ for i in range(self.config.pretraining_tp)
1410
+ ]
1411
+ logits = torch.cat(logits, dim=-1)
1412
+ else:
1413
+ logits = self.lm_head(
1414
+ hidden_states / (self.config.hidden_size / self.config.dim_model_base)
1415
+ )
1416
+ logits = logits.float()
1417
+
1418
+ loss = None
1419
+ if labels is not None:
1420
+ # Shift so that tokens < n predict n
1421
+ shift_logits = logits[..., :-1, :].contiguous()
1422
+ shift_labels = labels[..., 1:].contiguous()
1423
+ # Flatten the tokens
1424
+ loss_fct = CrossEntropyLoss()
1425
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1426
+ shift_labels = shift_labels.view(-1)
1427
+ # Enable model parallelism
1428
+ shift_labels = shift_labels.to(shift_logits.device)
1429
+ loss = loss_fct(shift_logits, shift_labels)
1430
+
1431
+ if not return_dict:
1432
+ output = (logits,) + outputs[1:]
1433
+ return (loss,) + output if loss is not None else output
1434
+
1435
+ return CausalLMOutputWithPast(
1436
+ loss=loss,
1437
+ logits=logits,
1438
+ past_key_values=outputs.past_key_values,
1439
+ hidden_states=outputs.hidden_states,
1440
+ attentions=outputs.attentions,
1441
+ )
1442
+
1443
+ def prepare_inputs_for_generation(
1444
+ self,
1445
+ input_ids,
1446
+ past_key_values=None,
1447
+ attention_mask=None,
1448
+ inputs_embeds=None,
1449
+ **kwargs,
1450
+ ):
1451
+ if past_key_values is not None:
1452
+ if isinstance(past_key_values, Cache):
1453
+ cache_length = past_key_values.get_seq_length()
1454
+ past_length = past_key_values.seen_tokens
1455
+ max_cache_length = past_key_values.get_max_length()
1456
+ else:
1457
+ cache_length = past_length = past_key_values[0][0].shape[2]
1458
+ max_cache_length = None
1459
+
1460
+ # Keep only the unprocessed tokens:
1461
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1462
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1463
+ # input)
1464
+ if (
1465
+ attention_mask is not None
1466
+ and attention_mask.shape[1] > input_ids.shape[1]
1467
+ ):
1468
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1469
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1470
+ # input_ids based on the past_length.
1471
+ elif past_length < input_ids.shape[1]:
1472
+ input_ids = input_ids[:, past_length:]
1473
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1474
+
1475
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1476
+ if (
1477
+ max_cache_length is not None
1478
+ and attention_mask is not None
1479
+ and cache_length + input_ids.shape[1] > max_cache_length
1480
+ ):
1481
+ attention_mask = attention_mask[:, -max_cache_length:]
1482
+
1483
+ position_ids = kwargs.get("position_ids", None)
1484
+ if attention_mask is not None and position_ids is None:
1485
+ # create position_ids on the fly for batch generation
1486
+ position_ids = attention_mask.long().cumsum(-1) - 1
1487
+ position_ids.masked_fill_(attention_mask == 0, 1)
1488
+ if past_key_values:
1489
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1490
+
1491
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1492
+ if inputs_embeds is not None and past_key_values is None:
1493
+ model_inputs = {"inputs_embeds": inputs_embeds}
1494
+ else:
1495
+ model_inputs = {"input_ids": input_ids}
1496
+
1497
+ model_inputs.update(
1498
+ {
1499
+ "position_ids": position_ids,
1500
+ "past_key_values": past_key_values,
1501
+ "use_cache": kwargs.get("use_cache"),
1502
+ "attention_mask": attention_mask,
1503
+ }
1504
+ )
1505
+ return model_inputs
1506
+
1507
+ @staticmethod
1508
+ def _reorder_cache(past_key_values, beam_idx):
1509
+ reordered_past = ()
1510
+ for layer_past in past_key_values:
1511
+ reordered_past += (
1512
+ tuple(
1513
+ past_state.index_select(0, beam_idx.to(past_state.device))
1514
+ for past_state in layer_past
1515
+ ),
1516
+ )
1517
+ return reordered_past
1518
+
1519
+ @torch.inference_mode()
1520
+ def chat(
1521
+ self,
1522
+ tokenizer,
1523
+ query: str,
1524
+ history: List[Dict] = None,
1525
+ role: str = "user",
1526
+ max_length: int = 4096,
1527
+ num_beams=1,
1528
+ do_sample=True,
1529
+ top_p=0.8,
1530
+ temperature=0.3,
1531
+ logits_processor=None,
1532
+ **kwargs,
1533
+ ):
1534
+ if history is None:
1535
+ history = []
1536
+ if logits_processor:
1537
+ gen_kwargs = {
1538
+ "max_length": max_length,
1539
+ "num_beams": num_beams,
1540
+ "do_sample": do_sample,
1541
+ "top_p": top_p,
1542
+ "temperature": temperature,
1543
+ "logits_processor": logits_processor,
1544
+ **kwargs,
1545
+ }
1546
+ else:
1547
+ gen_kwargs = {
1548
+ "max_length": max_length,
1549
+ "num_beams": num_beams,
1550
+ "do_sample": do_sample,
1551
+ "top_p": top_p,
1552
+ "temperature": temperature,
1553
+ "logits_processor": logits_processor,
1554
+ **kwargs,
1555
+ }
1556
+
1557
+ history.append({"role": role, "content": query})
1558
+ history_str = tokenizer.apply_chat_template(
1559
+ history, tokenize=False, add_generation_prompt=False
1560
+ )
1561
+ inputs = tokenizer(history_str, return_tensors="pt").to(self.device)
1562
+ outputs = self.generate(**inputs, **gen_kwargs)
1563
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]) : -1]
1564
+ response = tokenizer.decode(outputs)
1565
+ pattern = re.compile(r".*?(?=<AI>|<用户>)", re.DOTALL)
1566
+ matches = pattern.findall(response)
1567
+ if len(matches) > 0:
1568
+ response = matches[0]
1569
+ history.append({"role": "assistant", "content": response})
1570
+ return response, history
1571
+
1572
+
1573
+ @add_start_docstrings(
1574
+ """
1575
+ The CerboAI Model transformer with a sequence classification head on top (linear layer).
1576
+
1577
+ [`CerboAIForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1578
+ (e.g. GPT-2) do.
1579
+
1580
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1581
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1582
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1583
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1584
+ each row of the batch).
1585
+ """,
1586
+ CerboAI_START_DOCSTRING,
1587
+ )
1588
+ class CerboAIForSequenceClassification(CerboAIPreTrainedModel):
1589
+ def __init__(self, config):
1590
+ super().__init__(config)
1591
+ self.num_labels = config.num_labels
1592
+ self.model = CerboAIModel(config)
1593
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1594
+
1595
+ # Initialize weights and apply final processing
1596
+ self.post_init()
1597
+
1598
+ def get_input_embeddings(self):
1599
+ return self.model.embed_tokens
1600
+
1601
+ def set_input_embeddings(self, value):
1602
+ self.model.embed_tokens = value
1603
+
1604
+ @add_start_docstrings_to_model_forward(CerboAI_INPUTS_DOCSTRING)
1605
+ def forward(
1606
+ self,
1607
+ input_ids: torch.LongTensor = None,
1608
+ attention_mask: Optional[torch.Tensor] = None,
1609
+ position_ids: Optional[torch.LongTensor] = None,
1610
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1611
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1612
+ labels: Optional[torch.LongTensor] = None,
1613
+ use_cache: Optional[bool] = None,
1614
+ output_attentions: Optional[bool] = None,
1615
+ output_hidden_states: Optional[bool] = None,
1616
+ return_dict: Optional[bool] = None,
1617
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1618
+ r"""
1619
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1620
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1621
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1622
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1623
+ """
1624
+ return_dict = (
1625
+ return_dict if return_dict is not None else self.config.use_return_dict
1626
+ )
1627
+
1628
+ transformer_outputs = self.model(
1629
+ input_ids,
1630
+ attention_mask=attention_mask,
1631
+ position_ids=position_ids,
1632
+ past_key_values=past_key_values,
1633
+ inputs_embeds=inputs_embeds,
1634
+ use_cache=use_cache,
1635
+ output_attentions=output_attentions,
1636
+ output_hidden_states=output_hidden_states,
1637
+ return_dict=return_dict,
1638
+ )
1639
+ hidden_states = transformer_outputs[0]
1640
+ logits = self.score(hidden_states)
1641
+
1642
+ if input_ids is not None:
1643
+ batch_size = input_ids.shape[0]
1644
+ else:
1645
+ batch_size = inputs_embeds.shape[0]
1646
+
1647
+ if self.config.pad_token_id is None and batch_size != 1:
1648
+ raise ValueError(
1649
+ "Cannot handle batch sizes > 1 if no padding token is defined."
1650
+ )
1651
+ if self.config.pad_token_id is None:
1652
+ sequence_lengths = -1
1653
+ else:
1654
+ if input_ids is not None:
1655
+ sequence_lengths = (
1656
+ torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1657
+ ).to(logits.device)
1658
+ else:
1659
+ sequence_lengths = -1
1660
+
1661
+ pooled_logits = logits[
1662
+ torch.arange(batch_size, device=logits.device), sequence_lengths
1663
+ ]
1664
+
1665
+ loss = None
1666
+ if labels is not None:
1667
+ labels = labels.to(logits.device)
1668
+ if self.config.problem_type is None:
1669
+ if self.num_labels == 1:
1670
+ self.config.problem_type = "regression"
1671
+ elif self.num_labels > 1 and (
1672
+ labels.dtype == torch.long or labels.dtype == torch.int
1673
+ ):
1674
+ self.config.problem_type = "single_label_classification"
1675
+ else:
1676
+ self.config.problem_type = "multi_label_classification"
1677
+
1678
+ if self.config.problem_type == "regression":
1679
+ loss_fct = MSELoss()
1680
+ if self.num_labels == 1:
1681
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1682
+ else:
1683
+ loss = loss_fct(pooled_logits, labels)
1684
+ elif self.config.problem_type == "single_label_classification":
1685
+ loss_fct = CrossEntropyLoss()
1686
+ loss = loss_fct(
1687
+ pooled_logits.view(-1, self.num_labels), labels.view(-1)
1688
+ )
1689
+ elif self.config.problem_type == "multi_label_classification":
1690
+ loss_fct = BCEWithLogitsLoss()
1691
+ loss = loss_fct(pooled_logits, labels)
1692
+ if not return_dict:
1693
+ output = (pooled_logits,) + transformer_outputs[1:]
1694
+ return ((loss,) + output) if loss is not None else output
1695
+
1696
+ return SequenceClassifierOutputWithPast(
1697
+ loss=loss,
1698
+ logits=pooled_logits,
1699
+ past_key_values=transformer_outputs.past_key_values,
1700
+ hidden_states=transformer_outputs.hidden_states,
1701
+ attentions=transformer_outputs.attentions,
1702
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "pad_token": "</s>",
17
+ "unk_token": {
18
+ "content": "<unk>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ }
24
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c9aafcd7da1f5611dab6be545db74d5552a2ccc9c2a12c72ea7be63aac4a25d7
3
+ size 1994871
tokenizer_config.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "added_tokens_decoder": {
5
+ "0": {
6
+ "content": "<unk>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "1": {
14
+ "content": "<s>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "2": {
22
+ "content": "</s>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ }
29
+ },
30
+ "bos_token": "<s>",
31
+ "chat_template": "{{ '<s>' }}{% if messages[0]['role'] == 'system' %}{% set system_message = messages[0]['content'] %}{% endif %}{% if system_message is defined %}{{ system_message }}{% endif %}{% for message in messages %}{% set content = message['content'] %}{% if message['role'] == 'user' %}{{ '<用户>' + content + '<AI>' }}{% elif message['role'] == 'assistant' %}{{ content + '</s>' }}{% endif %}{% endfor %}",
32
+ "clean_up_tokenization_spaces": false,
33
+ "eos_token": "</s>",
34
+ "legacy": true,
35
+ "model_max_length": 1000000000000000019884624838656,
36
+ "pad_token": "</s>",
37
+ "padding_side": "left",
38
+ "sp_model_kwargs": {},
39
+ "spaces_between_special_tokens": false,
40
+ "split_special_tokens": false,
41
+ "tokenizer_class": "LlamaTokenizer",
42
+ "unk_token": "<unk>",
43
+ "use_default_system_prompt": false
44
+ }