hrsun15 commited on
Commit
02ccab2
1 Parent(s): af4fb27

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
added_tokens.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "<|im_end|>": 250681,
3
+ "<|im_start|>": 250680
4
+ }
config.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/data1/hrsun/FuxiTranyu-8B-Instruct",
3
+ "activation_function": "gelu_fast",
4
+ "architectures": [
5
+ "FuxiTranyuForCausalLM"
6
+ ],
7
+ "attention_bias": true,
8
+ "attention_dropout": 0.0,
9
+ "auto_map": {
10
+ "AutoConfig": "configuration_fuxitranyu.FuxiTranyuConfig",
11
+ "AutoModelForCausalLM": "modeling_fuxitranyu.FuxiTranyuForCausalLM"
12
+ },
13
+ "bos_token_id": 250680,
14
+ "eos_token_id": 250681,
15
+ "hidden_size": 4096,
16
+ "initializer_range": 0.01,
17
+ "intermediate_size": 16384,
18
+ "max_position_embeddings": 4096,
19
+ "model_type": "fuxitranyu",
20
+ "num_attention_heads": 32,
21
+ "num_hidden_layers": 30,
22
+ "num_key_value_heads": 32,
23
+ "pad_token_id": 250681,
24
+ "pretraining_tp": 1,
25
+ "rms_norm_eps": 1e-05,
26
+ "rope_scaling": null,
27
+ "rope_theta": 10000.0,
28
+ "tie_word_embeddings": false,
29
+ "tokenizer_class": "GPT2TokenizerFast",
30
+ "torch_dtype": "float16",
31
+ "transformers_version": "4.42.4",
32
+ "use_cache": true,
33
+ "vocab_size": 250682
34
+ }
configuration_fuxitranyu.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ FuxiTranyu model configuration"""
2
+
3
+ from transformers.configuration_utils import PretrainedConfig
4
+ from transformers.utils import logging
5
+
6
+ logger = logging.get_logger(__name__)
7
+
8
+ FUXITRANYU_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
9
+
10
+
11
+ class FuxiTranyuConfig(PretrainedConfig):
12
+ r"""
13
+ This is the configuration class to store the configuration of a [`FuxitranyuModel`]. It is used to instantiate an FuxiTranyu
14
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
15
+ defaults will yield a similar configuration to that of the FuxiTranyu-7B.
16
+
17
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
18
+ documentation from [`PretrainedConfig`] for more information.
19
+
20
+
21
+ Args:
22
+ vocab_size (`int`, *optional*, defaults to 32000):
23
+ Vocabulary size of the FuxiTranyu model. Defines the number of different tokens that can be represented by the
24
+ `inputs_ids` passed when calling [`FuxitranyuModel`]
25
+ hidden_size (`int`, *optional*, defaults to 4096):
26
+ Dimension of the hidden representations.
27
+ intermediate_size (`int`, *optional*, defaults to 11008):
28
+ Dimension of the MLP representations.
29
+ num_hidden_layers (`int`, *optional*, defaults to 32):
30
+ Number of hidden layers in the Transformer decoder.
31
+ num_attention_heads (`int`, *optional*, defaults to 32):
32
+ Number of attention heads for each attention layer in the Transformer decoder.
33
+ num_key_value_heads (`int`, *optional*):
34
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
35
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
36
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
37
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
38
+ by meanpooling all the original heads within that group. For more details checkout [this
39
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
40
+ `num_attention_heads`.
41
+ activation_function (`str` or `function`, *optional*, defaults to `"silu"`):
42
+ The non-linear activation function (function or string) in the decoder.
43
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
44
+ The maximum sequence length that this model might ever be used with. FuxiTranyu v1 supports up to 4096 tokens.
45
+ initializer_range (`float`, *optional*, defaults to 0.02):
46
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
47
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
48
+ The epsilon used by the rms normalization layers.
49
+ use_cache (`bool`, *optional*, defaults to `True`):
50
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
51
+ relevant if `config.is_decoder=True`.
52
+ pad_token_id (`int`, *optional*):
53
+ Padding token id.
54
+ bos_token_id (`int`, *optional*, defaults to 1):
55
+ Beginning of stream token id.
56
+ eos_token_id (`int`, *optional*, defaults to 2):
57
+ End of stream token id.
58
+ pretraining_tp (`int`, *optional*, defaults to 1):
59
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
60
+ document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to understand more about it. This value is
61
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
62
+ issue](https://github.com/pytorch/pytorch/issues/76232).
63
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
64
+ Whether to tie weight embeddings
65
+ rope_theta (`float`, *optional*, defaults to 10000.0):
66
+ The base period of the RoPE embeddings.
67
+ rope_scaling (`Dict`, *optional*):
68
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
69
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
70
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
71
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
72
+ these scaling strategies behave:
73
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
74
+ experimental feature, subject to breaking API changes in future versions.
75
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
76
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
77
+ attention_dropout (`float`, *optional*, defaults to 0.0):
78
+ The dropout ratio for the attention probabilities.
79
+
80
+ ```python
81
+ >>> from transformers import FuxitranyuModel, FuxitranyuConfig
82
+
83
+ >>> # Initializing a FuxiTranyu Fuxitranyu-7b style configuration
84
+ >>> configuration = FuxitranyuConfig()
85
+
86
+ >>> # Initializing a model from the fuxitranyu-7b style configuration
87
+ >>> model = FuxitranyuModel(configuration)
88
+
89
+ >>> # Accessing the model configuration
90
+ >>> configuration = model.config
91
+ ```"""
92
+
93
+ model_type = "fuxitranyu"
94
+ keys_to_ignore_at_inference = ["past_key_values"]
95
+
96
+ def __init__(
97
+ self,
98
+ vocab_size=250752,
99
+ hidden_size=4096,
100
+ intermediate_size=16384,
101
+ num_hidden_layers=30,
102
+ num_attention_heads=32,
103
+ num_key_value_heads=None,
104
+ activation_function="gelu_fast",
105
+ max_position_embeddings=4096,
106
+ initializer_range=0.01,
107
+ rms_norm_eps=1e-5,
108
+ use_cache=True,
109
+ pad_token_id=None,
110
+ bos_token_id=0,
111
+ eos_token_id=0,
112
+ pretraining_tp=1,
113
+ tie_word_embeddings=False,
114
+ rope_theta=10000.0,
115
+ rope_scaling=None,
116
+ attention_bias=True,
117
+ attention_dropout=0.0,
118
+ **kwargs,
119
+ ):
120
+ self.vocab_size = vocab_size
121
+ self.max_position_embeddings = max_position_embeddings
122
+ self.hidden_size = hidden_size
123
+ self.intermediate_size = intermediate_size
124
+ self.num_hidden_layers = num_hidden_layers
125
+ self.num_attention_heads = num_attention_heads
126
+
127
+ # for backward compatibility
128
+ if num_key_value_heads is None:
129
+ num_key_value_heads = num_attention_heads
130
+
131
+ self.num_key_value_heads = num_key_value_heads
132
+ self.activation_function = activation_function
133
+ self.initializer_range = initializer_range
134
+ self.rms_norm_eps = rms_norm_eps
135
+ self.pretraining_tp = pretraining_tp
136
+ self.use_cache = use_cache
137
+ self.rope_theta = rope_theta
138
+ self.rope_scaling = rope_scaling
139
+ self._rope_scaling_validation()
140
+ self.attention_bias = attention_bias
141
+ self.attention_dropout = attention_dropout
142
+
143
+ super().__init__(
144
+ pad_token_id=pad_token_id,
145
+ bos_token_id=bos_token_id,
146
+ eos_token_id=eos_token_id,
147
+ tie_word_embeddings=tie_word_embeddings,
148
+ **kwargs,
149
+ )
150
+
151
+ def _rope_scaling_validation(self):
152
+ """
153
+ Validate the `rope_scaling` configuration.
154
+ """
155
+ if self.rope_scaling is None:
156
+ return
157
+
158
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
159
+ raise ValueError(
160
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
161
+ f"got {self.rope_scaling}"
162
+ )
163
+ rope_scaling_type = self.rope_scaling.get("type", None)
164
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
165
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic", 'yarn']:
166
+ raise ValueError(
167
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic', 'yarn], got {rope_scaling_type}"
168
+ )
169
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
170
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
171
+ if rope_scaling_type == "yarn" or rope_scaling_type == "dynamic-yarn":
172
+ original_max_position_embeddings = self.rope_scaling.get("original_max_position_embeddings", None)
173
+ if original_max_position_embeddings is None or not isinstance(original_max_position_embeddings, int):
174
+ raise ValueError(f"`rope_scaling.original_max_position_embeddings` must be set to an int when using yarn, and dynamic-yarn")
generation_config.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 250680,
4
+ "eos_token_id": 250681,
5
+ "pad_token_id": 250681,
6
+ "transformers_version": "4.42.4",
7
+ "use_cache": false
8
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model-00001-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e060a6581b5116ff4bb7172c13b287a799d0a8d186096b1fbadb9cdd74261d17
3
+ size 4973489664
model-00002-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:28bdaa6b18bdd4e85c010971a0e5f6bc1f83e7af9e2d93fab88155d0d312973f
3
+ size 4866501280
model-00003-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e649d8640756cfcd591b042a8f7536b9b6c72f3b9d88f022d77f8b49e135a969
3
+ size 4295950472
model-00004-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d2b95588d6db503eeeac30554b5ce60602e3ee19b883de4f33a68ce483c99c5e
3
+ size 2053587072
model.safetensors.index.json ADDED
@@ -0,0 +1,430 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 16189480960
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-00004-of-00004.safetensors",
7
+ "model.embed_tokens.weight": "model-00001-of-00004.safetensors",
8
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00004.safetensors",
9
+ "model.layers.0.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
10
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
11
+ "model.layers.0.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
12
+ "model.layers.0.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
13
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
14
+ "model.layers.0.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
15
+ "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
16
+ "model.layers.0.self_attn.o_proj.bias": "model-00001-of-00004.safetensors",
17
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
18
+ "model.layers.0.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
19
+ "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
20
+ "model.layers.0.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
21
+ "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
22
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00004.safetensors",
23
+ "model.layers.1.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
24
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
25
+ "model.layers.1.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
26
+ "model.layers.1.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
27
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
28
+ "model.layers.1.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
29
+ "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
30
+ "model.layers.1.self_attn.o_proj.bias": "model-00001-of-00004.safetensors",
31
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
32
+ "model.layers.1.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
33
+ "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
34
+ "model.layers.1.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
35
+ "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
36
+ "model.layers.10.input_layernorm.weight": "model-00002-of-00004.safetensors",
37
+ "model.layers.10.mlp.down_proj.bias": "model-00002-of-00004.safetensors",
38
+ "model.layers.10.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
39
+ "model.layers.10.mlp.up_proj.bias": "model-00002-of-00004.safetensors",
40
+ "model.layers.10.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
41
+ "model.layers.10.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
42
+ "model.layers.10.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
43
+ "model.layers.10.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
44
+ "model.layers.10.self_attn.o_proj.bias": "model-00002-of-00004.safetensors",
45
+ "model.layers.10.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
46
+ "model.layers.10.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
47
+ "model.layers.10.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
48
+ "model.layers.10.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
49
+ "model.layers.10.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
50
+ "model.layers.11.input_layernorm.weight": "model-00002-of-00004.safetensors",
51
+ "model.layers.11.mlp.down_proj.bias": "model-00002-of-00004.safetensors",
52
+ "model.layers.11.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
53
+ "model.layers.11.mlp.up_proj.bias": "model-00002-of-00004.safetensors",
54
+ "model.layers.11.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
55
+ "model.layers.11.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
56
+ "model.layers.11.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
57
+ "model.layers.11.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
58
+ "model.layers.11.self_attn.o_proj.bias": "model-00002-of-00004.safetensors",
59
+ "model.layers.11.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
60
+ "model.layers.11.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
61
+ "model.layers.11.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
62
+ "model.layers.11.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
63
+ "model.layers.11.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
64
+ "model.layers.12.input_layernorm.weight": "model-00002-of-00004.safetensors",
65
+ "model.layers.12.mlp.down_proj.bias": "model-00002-of-00004.safetensors",
66
+ "model.layers.12.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
67
+ "model.layers.12.mlp.up_proj.bias": "model-00002-of-00004.safetensors",
68
+ "model.layers.12.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
69
+ "model.layers.12.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
70
+ "model.layers.12.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
71
+ "model.layers.12.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
72
+ "model.layers.12.self_attn.o_proj.bias": "model-00002-of-00004.safetensors",
73
+ "model.layers.12.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
74
+ "model.layers.12.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
75
+ "model.layers.12.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
76
+ "model.layers.12.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
77
+ "model.layers.12.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
78
+ "model.layers.13.input_layernorm.weight": "model-00002-of-00004.safetensors",
79
+ "model.layers.13.mlp.down_proj.bias": "model-00002-of-00004.safetensors",
80
+ "model.layers.13.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
81
+ "model.layers.13.mlp.up_proj.bias": "model-00002-of-00004.safetensors",
82
+ "model.layers.13.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
83
+ "model.layers.13.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
84
+ "model.layers.13.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
85
+ "model.layers.13.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
86
+ "model.layers.13.self_attn.o_proj.bias": "model-00002-of-00004.safetensors",
87
+ "model.layers.13.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
88
+ "model.layers.13.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
89
+ "model.layers.13.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
90
+ "model.layers.13.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
91
+ "model.layers.13.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
92
+ "model.layers.14.input_layernorm.weight": "model-00002-of-00004.safetensors",
93
+ "model.layers.14.mlp.down_proj.bias": "model-00002-of-00004.safetensors",
94
+ "model.layers.14.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
95
+ "model.layers.14.mlp.up_proj.bias": "model-00002-of-00004.safetensors",
96
+ "model.layers.14.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
97
+ "model.layers.14.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
98
+ "model.layers.14.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
99
+ "model.layers.14.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
100
+ "model.layers.14.self_attn.o_proj.bias": "model-00002-of-00004.safetensors",
101
+ "model.layers.14.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
102
+ "model.layers.14.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
103
+ "model.layers.14.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
104
+ "model.layers.14.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
105
+ "model.layers.14.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
106
+ "model.layers.15.input_layernorm.weight": "model-00002-of-00004.safetensors",
107
+ "model.layers.15.mlp.down_proj.bias": "model-00002-of-00004.safetensors",
108
+ "model.layers.15.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
109
+ "model.layers.15.mlp.up_proj.bias": "model-00002-of-00004.safetensors",
110
+ "model.layers.15.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
111
+ "model.layers.15.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
112
+ "model.layers.15.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
113
+ "model.layers.15.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
114
+ "model.layers.15.self_attn.o_proj.bias": "model-00002-of-00004.safetensors",
115
+ "model.layers.15.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
116
+ "model.layers.15.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
117
+ "model.layers.15.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
118
+ "model.layers.15.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
119
+ "model.layers.15.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
120
+ "model.layers.16.input_layernorm.weight": "model-00002-of-00004.safetensors",
121
+ "model.layers.16.mlp.down_proj.bias": "model-00002-of-00004.safetensors",
122
+ "model.layers.16.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
123
+ "model.layers.16.mlp.up_proj.bias": "model-00002-of-00004.safetensors",
124
+ "model.layers.16.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
125
+ "model.layers.16.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
126
+ "model.layers.16.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
127
+ "model.layers.16.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
128
+ "model.layers.16.self_attn.o_proj.bias": "model-00002-of-00004.safetensors",
129
+ "model.layers.16.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
130
+ "model.layers.16.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
131
+ "model.layers.16.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
132
+ "model.layers.16.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
133
+ "model.layers.16.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
134
+ "model.layers.17.input_layernorm.weight": "model-00002-of-00004.safetensors",
135
+ "model.layers.17.mlp.down_proj.bias": "model-00002-of-00004.safetensors",
136
+ "model.layers.17.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
137
+ "model.layers.17.mlp.up_proj.bias": "model-00002-of-00004.safetensors",
138
+ "model.layers.17.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
139
+ "model.layers.17.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
140
+ "model.layers.17.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
141
+ "model.layers.17.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
142
+ "model.layers.17.self_attn.o_proj.bias": "model-00002-of-00004.safetensors",
143
+ "model.layers.17.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
144
+ "model.layers.17.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
145
+ "model.layers.17.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
146
+ "model.layers.17.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
147
+ "model.layers.17.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
148
+ "model.layers.18.input_layernorm.weight": "model-00002-of-00004.safetensors",
149
+ "model.layers.18.mlp.down_proj.bias": "model-00002-of-00004.safetensors",
150
+ "model.layers.18.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
151
+ "model.layers.18.mlp.up_proj.bias": "model-00002-of-00004.safetensors",
152
+ "model.layers.18.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
153
+ "model.layers.18.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
154
+ "model.layers.18.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
155
+ "model.layers.18.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
156
+ "model.layers.18.self_attn.o_proj.bias": "model-00002-of-00004.safetensors",
157
+ "model.layers.18.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
158
+ "model.layers.18.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
159
+ "model.layers.18.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
160
+ "model.layers.18.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
161
+ "model.layers.18.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
162
+ "model.layers.19.input_layernorm.weight": "model-00003-of-00004.safetensors",
163
+ "model.layers.19.mlp.down_proj.bias": "model-00003-of-00004.safetensors",
164
+ "model.layers.19.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
165
+ "model.layers.19.mlp.up_proj.bias": "model-00003-of-00004.safetensors",
166
+ "model.layers.19.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
167
+ "model.layers.19.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
168
+ "model.layers.19.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
169
+ "model.layers.19.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
170
+ "model.layers.19.self_attn.o_proj.bias": "model-00002-of-00004.safetensors",
171
+ "model.layers.19.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
172
+ "model.layers.19.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
173
+ "model.layers.19.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
174
+ "model.layers.19.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
175
+ "model.layers.19.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
176
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00004.safetensors",
177
+ "model.layers.2.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
178
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
179
+ "model.layers.2.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
180
+ "model.layers.2.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
181
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
182
+ "model.layers.2.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
183
+ "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
184
+ "model.layers.2.self_attn.o_proj.bias": "model-00001-of-00004.safetensors",
185
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
186
+ "model.layers.2.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
187
+ "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
188
+ "model.layers.2.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
189
+ "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
190
+ "model.layers.20.input_layernorm.weight": "model-00003-of-00004.safetensors",
191
+ "model.layers.20.mlp.down_proj.bias": "model-00003-of-00004.safetensors",
192
+ "model.layers.20.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
193
+ "model.layers.20.mlp.up_proj.bias": "model-00003-of-00004.safetensors",
194
+ "model.layers.20.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
195
+ "model.layers.20.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
196
+ "model.layers.20.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
197
+ "model.layers.20.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
198
+ "model.layers.20.self_attn.o_proj.bias": "model-00003-of-00004.safetensors",
199
+ "model.layers.20.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
200
+ "model.layers.20.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
201
+ "model.layers.20.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
202
+ "model.layers.20.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
203
+ "model.layers.20.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
204
+ "model.layers.21.input_layernorm.weight": "model-00003-of-00004.safetensors",
205
+ "model.layers.21.mlp.down_proj.bias": "model-00003-of-00004.safetensors",
206
+ "model.layers.21.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
207
+ "model.layers.21.mlp.up_proj.bias": "model-00003-of-00004.safetensors",
208
+ "model.layers.21.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
209
+ "model.layers.21.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
210
+ "model.layers.21.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
211
+ "model.layers.21.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
212
+ "model.layers.21.self_attn.o_proj.bias": "model-00003-of-00004.safetensors",
213
+ "model.layers.21.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
214
+ "model.layers.21.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
215
+ "model.layers.21.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
216
+ "model.layers.21.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
217
+ "model.layers.21.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
218
+ "model.layers.22.input_layernorm.weight": "model-00003-of-00004.safetensors",
219
+ "model.layers.22.mlp.down_proj.bias": "model-00003-of-00004.safetensors",
220
+ "model.layers.22.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
221
+ "model.layers.22.mlp.up_proj.bias": "model-00003-of-00004.safetensors",
222
+ "model.layers.22.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
223
+ "model.layers.22.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
224
+ "model.layers.22.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
225
+ "model.layers.22.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
226
+ "model.layers.22.self_attn.o_proj.bias": "model-00003-of-00004.safetensors",
227
+ "model.layers.22.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
228
+ "model.layers.22.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
229
+ "model.layers.22.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
230
+ "model.layers.22.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
231
+ "model.layers.22.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
232
+ "model.layers.23.input_layernorm.weight": "model-00003-of-00004.safetensors",
233
+ "model.layers.23.mlp.down_proj.bias": "model-00003-of-00004.safetensors",
234
+ "model.layers.23.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
235
+ "model.layers.23.mlp.up_proj.bias": "model-00003-of-00004.safetensors",
236
+ "model.layers.23.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
237
+ "model.layers.23.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
238
+ "model.layers.23.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
239
+ "model.layers.23.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
240
+ "model.layers.23.self_attn.o_proj.bias": "model-00003-of-00004.safetensors",
241
+ "model.layers.23.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
242
+ "model.layers.23.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
243
+ "model.layers.23.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
244
+ "model.layers.23.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
245
+ "model.layers.23.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
246
+ "model.layers.24.input_layernorm.weight": "model-00003-of-00004.safetensors",
247
+ "model.layers.24.mlp.down_proj.bias": "model-00003-of-00004.safetensors",
248
+ "model.layers.24.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
249
+ "model.layers.24.mlp.up_proj.bias": "model-00003-of-00004.safetensors",
250
+ "model.layers.24.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
251
+ "model.layers.24.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
252
+ "model.layers.24.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
253
+ "model.layers.24.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
254
+ "model.layers.24.self_attn.o_proj.bias": "model-00003-of-00004.safetensors",
255
+ "model.layers.24.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
256
+ "model.layers.24.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
257
+ "model.layers.24.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
258
+ "model.layers.24.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
259
+ "model.layers.24.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
260
+ "model.layers.25.input_layernorm.weight": "model-00003-of-00004.safetensors",
261
+ "model.layers.25.mlp.down_proj.bias": "model-00003-of-00004.safetensors",
262
+ "model.layers.25.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
263
+ "model.layers.25.mlp.up_proj.bias": "model-00003-of-00004.safetensors",
264
+ "model.layers.25.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
265
+ "model.layers.25.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
266
+ "model.layers.25.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
267
+ "model.layers.25.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
268
+ "model.layers.25.self_attn.o_proj.bias": "model-00003-of-00004.safetensors",
269
+ "model.layers.25.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
270
+ "model.layers.25.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
271
+ "model.layers.25.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
272
+ "model.layers.25.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
273
+ "model.layers.25.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
274
+ "model.layers.26.input_layernorm.weight": "model-00003-of-00004.safetensors",
275
+ "model.layers.26.mlp.down_proj.bias": "model-00003-of-00004.safetensors",
276
+ "model.layers.26.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
277
+ "model.layers.26.mlp.up_proj.bias": "model-00003-of-00004.safetensors",
278
+ "model.layers.26.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
279
+ "model.layers.26.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
280
+ "model.layers.26.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
281
+ "model.layers.26.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
282
+ "model.layers.26.self_attn.o_proj.bias": "model-00003-of-00004.safetensors",
283
+ "model.layers.26.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
284
+ "model.layers.26.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
285
+ "model.layers.26.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
286
+ "model.layers.26.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
287
+ "model.layers.26.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
288
+ "model.layers.27.input_layernorm.weight": "model-00003-of-00004.safetensors",
289
+ "model.layers.27.mlp.down_proj.bias": "model-00003-of-00004.safetensors",
290
+ "model.layers.27.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
291
+ "model.layers.27.mlp.up_proj.bias": "model-00003-of-00004.safetensors",
292
+ "model.layers.27.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
293
+ "model.layers.27.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
294
+ "model.layers.27.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
295
+ "model.layers.27.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
296
+ "model.layers.27.self_attn.o_proj.bias": "model-00003-of-00004.safetensors",
297
+ "model.layers.27.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
298
+ "model.layers.27.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
299
+ "model.layers.27.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
300
+ "model.layers.27.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
301
+ "model.layers.27.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
302
+ "model.layers.28.input_layernorm.weight": "model-00003-of-00004.safetensors",
303
+ "model.layers.28.mlp.down_proj.bias": "model-00003-of-00004.safetensors",
304
+ "model.layers.28.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
305
+ "model.layers.28.mlp.up_proj.bias": "model-00003-of-00004.safetensors",
306
+ "model.layers.28.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
307
+ "model.layers.28.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
308
+ "model.layers.28.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
309
+ "model.layers.28.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
310
+ "model.layers.28.self_attn.o_proj.bias": "model-00003-of-00004.safetensors",
311
+ "model.layers.28.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
312
+ "model.layers.28.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
313
+ "model.layers.28.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
314
+ "model.layers.28.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
315
+ "model.layers.28.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
316
+ "model.layers.29.input_layernorm.weight": "model-00003-of-00004.safetensors",
317
+ "model.layers.29.mlp.down_proj.bias": "model-00003-of-00004.safetensors",
318
+ "model.layers.29.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
319
+ "model.layers.29.mlp.up_proj.bias": "model-00003-of-00004.safetensors",
320
+ "model.layers.29.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
321
+ "model.layers.29.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
322
+ "model.layers.29.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
323
+ "model.layers.29.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
324
+ "model.layers.29.self_attn.o_proj.bias": "model-00003-of-00004.safetensors",
325
+ "model.layers.29.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
326
+ "model.layers.29.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
327
+ "model.layers.29.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
328
+ "model.layers.29.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
329
+ "model.layers.29.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
330
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00004.safetensors",
331
+ "model.layers.3.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
332
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
333
+ "model.layers.3.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
334
+ "model.layers.3.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
335
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
336
+ "model.layers.3.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
337
+ "model.layers.3.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
338
+ "model.layers.3.self_attn.o_proj.bias": "model-00001-of-00004.safetensors",
339
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
340
+ "model.layers.3.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
341
+ "model.layers.3.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
342
+ "model.layers.3.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
343
+ "model.layers.3.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
344
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00004.safetensors",
345
+ "model.layers.4.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
346
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
347
+ "model.layers.4.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
348
+ "model.layers.4.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
349
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
350
+ "model.layers.4.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
351
+ "model.layers.4.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
352
+ "model.layers.4.self_attn.o_proj.bias": "model-00001-of-00004.safetensors",
353
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
354
+ "model.layers.4.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
355
+ "model.layers.4.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
356
+ "model.layers.4.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
357
+ "model.layers.4.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
358
+ "model.layers.5.input_layernorm.weight": "model-00001-of-00004.safetensors",
359
+ "model.layers.5.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
360
+ "model.layers.5.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
361
+ "model.layers.5.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
362
+ "model.layers.5.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
363
+ "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
364
+ "model.layers.5.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
365
+ "model.layers.5.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
366
+ "model.layers.5.self_attn.o_proj.bias": "model-00001-of-00004.safetensors",
367
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
368
+ "model.layers.5.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
369
+ "model.layers.5.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
370
+ "model.layers.5.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
371
+ "model.layers.5.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
372
+ "model.layers.6.input_layernorm.weight": "model-00001-of-00004.safetensors",
373
+ "model.layers.6.mlp.down_proj.bias": "model-00001-of-00004.safetensors",
374
+ "model.layers.6.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
375
+ "model.layers.6.mlp.up_proj.bias": "model-00001-of-00004.safetensors",
376
+ "model.layers.6.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
377
+ "model.layers.6.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
378
+ "model.layers.6.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
379
+ "model.layers.6.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
380
+ "model.layers.6.self_attn.o_proj.bias": "model-00001-of-00004.safetensors",
381
+ "model.layers.6.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
382
+ "model.layers.6.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
383
+ "model.layers.6.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
384
+ "model.layers.6.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
385
+ "model.layers.6.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
386
+ "model.layers.7.input_layernorm.weight": "model-00002-of-00004.safetensors",
387
+ "model.layers.7.mlp.down_proj.bias": "model-00002-of-00004.safetensors",
388
+ "model.layers.7.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
389
+ "model.layers.7.mlp.up_proj.bias": "model-00002-of-00004.safetensors",
390
+ "model.layers.7.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
391
+ "model.layers.7.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
392
+ "model.layers.7.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
393
+ "model.layers.7.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
394
+ "model.layers.7.self_attn.o_proj.bias": "model-00002-of-00004.safetensors",
395
+ "model.layers.7.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
396
+ "model.layers.7.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
397
+ "model.layers.7.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
398
+ "model.layers.7.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
399
+ "model.layers.7.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
400
+ "model.layers.8.input_layernorm.weight": "model-00002-of-00004.safetensors",
401
+ "model.layers.8.mlp.down_proj.bias": "model-00002-of-00004.safetensors",
402
+ "model.layers.8.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
403
+ "model.layers.8.mlp.up_proj.bias": "model-00002-of-00004.safetensors",
404
+ "model.layers.8.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
405
+ "model.layers.8.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
406
+ "model.layers.8.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
407
+ "model.layers.8.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
408
+ "model.layers.8.self_attn.o_proj.bias": "model-00002-of-00004.safetensors",
409
+ "model.layers.8.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
410
+ "model.layers.8.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
411
+ "model.layers.8.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
412
+ "model.layers.8.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
413
+ "model.layers.8.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
414
+ "model.layers.9.input_layernorm.weight": "model-00002-of-00004.safetensors",
415
+ "model.layers.9.mlp.down_proj.bias": "model-00002-of-00004.safetensors",
416
+ "model.layers.9.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
417
+ "model.layers.9.mlp.up_proj.bias": "model-00002-of-00004.safetensors",
418
+ "model.layers.9.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
419
+ "model.layers.9.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
420
+ "model.layers.9.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
421
+ "model.layers.9.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
422
+ "model.layers.9.self_attn.o_proj.bias": "model-00002-of-00004.safetensors",
423
+ "model.layers.9.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
424
+ "model.layers.9.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
425
+ "model.layers.9.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
426
+ "model.layers.9.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
427
+ "model.layers.9.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
428
+ "model.norm.weight": "model-00003-of-00004.safetensors"
429
+ }
430
+ }
modeling_fuxitranyu.py ADDED
@@ -0,0 +1,1484 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ import math
3
+ import warnings
4
+ from typing import List, Optional, Tuple, Union
5
+
6
+ import torch
7
+ import torch.nn.functional as F
8
+ import torch.utils.checkpoint
9
+ from torch import nn
10
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
11
+
12
+ from transformers.activations import ACT2FN
13
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
14
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
15
+ from transformers.modeling_outputs import (
16
+ BaseModelOutputWithPast,
17
+ CausalLMOutputWithPast,
18
+ QuestionAnsweringModelOutput,
19
+ SequenceClassifierOutputWithPast,
20
+ )
21
+ from transformers.modeling_utils import PreTrainedModel
22
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
23
+ from transformers.utils import (
24
+ add_start_docstrings,
25
+ add_start_docstrings_to_model_forward,
26
+ is_flash_attn_2_available,
27
+ is_flash_attn_greater_or_equal_2_10,
28
+ logging,
29
+ replace_return_docstrings,
30
+ )
31
+ from .configuration_fuxitranyu import FuxiTranyuConfig
32
+
33
+
34
+ if is_flash_attn_2_available():
35
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
36
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
37
+
38
+
39
+ logger = logging.get_logger(__name__)
40
+
41
+ _CONFIG_FOR_DOC = "FuxiTranyuConfig"
42
+
43
+
44
+ def _get_unpad_data(attention_mask):
45
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
46
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
47
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
48
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
49
+ return (
50
+ indices,
51
+ cu_seqlens,
52
+ max_seqlen_in_batch,
53
+ )
54
+
55
+
56
+ class FuxiTranyuRMSNorm(nn.Module):
57
+ def __init__(self, hidden_size, eps=1e-6):
58
+ super().__init__()
59
+ self.weight = nn.Parameter(torch.ones(hidden_size))
60
+ self.variance_epsilon = eps
61
+
62
+ def forward(self, hidden_states):
63
+ input_dtype = hidden_states.dtype
64
+ hidden_states = hidden_states.to(torch.float32)
65
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
66
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
67
+ return self.weight * hidden_states.to(input_dtype)
68
+
69
+ ALL_LAYERNORM_LAYERS.append(FuxiTranyuRMSNorm)
70
+
71
+
72
+ class FuxiTranyuRotaryEmbedding(nn.Module):
73
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
74
+ super().__init__()
75
+ self.scaling_factor = scaling_factor
76
+ self.dim = dim
77
+ self.max_position_embeddings = max_position_embeddings
78
+ self.base = base
79
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
80
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
81
+ # For BC we register cos and sin cached
82
+ self.max_seq_len_cached = max_position_embeddings
83
+
84
+ @torch.no_grad()
85
+ def forward(self, x, position_ids):
86
+ # x: [bs, num_attention_heads, seq_len, head_size]
87
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
88
+ position_ids_expanded = position_ids[:, None, :].float()
89
+ # Force float32 since bfloat16 loses precision on long contexts
90
+ # See https://github.com/huggingface/transformers/pull/29285
91
+ device_type = x.device.type
92
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
93
+ with torch.autocast(device_type=device_type, enabled=False):
94
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
95
+ emb = torch.cat((freqs, freqs), dim=-1)
96
+ cos = emb.cos()
97
+ sin = emb.sin()
98
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
99
+
100
+
101
+ class FuxiTranyuLinearScalingRotaryEmbedding(FuxiTranyuRotaryEmbedding):
102
+ """FuxiTranyuRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
103
+
104
+ def forward(self, x, position_ids):
105
+ # difference to the original RoPE: a scaling factor is aplied to the position ids
106
+ position_ids = position_ids.float() / self.scaling_factor
107
+ cos, sin = super().forward(x, position_ids)
108
+ return cos, sin
109
+
110
+
111
+ class FuxiTranyuDynamicNTKScalingRotaryEmbedding(FuxiTranyuRotaryEmbedding):
112
+ """FuxiTranyuRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
113
+
114
+ def forward(self, x, position_ids):
115
+ # difference to the original RoPE: inv_freq is recomputed when the sequence length > original length
116
+ seq_len = torch.max(position_ids) + 1
117
+ if seq_len > self.max_position_embeddings:
118
+ base = self.base * (
119
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
120
+ ) ** (self.dim / (self.dim - 2))
121
+ inv_freq = 1.0 / (
122
+ base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(x.device) / self.dim)
123
+ )
124
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: this may break with compilation
125
+
126
+ cos, sin = super().forward(x, position_ids)
127
+ return cos, sin
128
+
129
+
130
+ def rotate_half(x):
131
+ """Rotates half the hidden dims of the input."""
132
+ x1 = x[..., : x.shape[-1] // 2]
133
+ x2 = x[..., x.shape[-1] // 2 :]
134
+ return torch.cat((-x2, x1), dim=-1)
135
+
136
+
137
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
138
+ """Applies Rotary Position Embedding to the query and key tensors.
139
+
140
+ Args:
141
+ q (`torch.Tensor`): The query tensor.
142
+ k (`torch.Tensor`): The key tensor.
143
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
144
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
145
+ position_ids (`torch.Tensor`, *optional*):
146
+ Deprecated and unused.
147
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
148
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
149
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
150
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
151
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
152
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
153
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
154
+ Returns:
155
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
156
+ """
157
+ cos = cos.unsqueeze(unsqueeze_dim)
158
+ sin = sin.unsqueeze(unsqueeze_dim)
159
+ q_embed = (q * cos) + (rotate_half(q) * sin)
160
+ k_embed = (k * cos) + (rotate_half(k) * sin)
161
+ return q_embed, k_embed
162
+
163
+ import torch
164
+ import math
165
+
166
+ # Inverse dim formula to find dim based on number of rotations
167
+ def find_correction_dim(num_rotations, dim, base=10000, max_position_embeddings=2048):
168
+ return (dim * math.log(max_position_embeddings/(num_rotations * 2 * math.pi)))/(2 * math.log(base))
169
+
170
+ # Find dim range bounds based on rotations
171
+ def find_correction_range(low_rot, high_rot, dim, base=10000, max_position_embeddings=2048):
172
+ low = math.floor(find_correction_dim(
173
+ low_rot, dim, base, max_position_embeddings))
174
+ high = math.ceil(find_correction_dim(
175
+ high_rot, dim, base, max_position_embeddings))
176
+ return max(low, 0), min(high, dim-1) # Clamp values just in case
177
+
178
+ def linear_ramp_mask(min, max, dim):
179
+ if min == max:
180
+ max += 0.001 # Prevent singularity
181
+
182
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
183
+ ramp_func = torch.clamp(linear_func, 0, 1)
184
+ return ramp_func
185
+
186
+ def get_mscale(scale=1):
187
+ if scale <= 1:
188
+ return 1.0
189
+ return 0.1 * math.log(scale) + 1.0
190
+
191
+ class FuxiTranyuYaRNScaledRotaryEmbedding(torch.nn.Module):
192
+ # adopted from YaRN FuxiTranyuYaRNScaledRotaryEmbedding https://github1s.com/jquesnelle/yarn/blob/master/scaled_rope/FuxiTranyuYaRNScaledRotaryEmbedding.py#L43
193
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, scale=1, original_max_position_embeddings=2048, extrapolation_factor=1, attn_factor=1, beta_fast=32, beta_slow=1, finetuned=False, device=None):
194
+ super().__init__()
195
+
196
+ self.dim = dim
197
+ self.max_position_embeddings = max_position_embeddings
198
+ self.base = base
199
+ self.scale = scale
200
+ self.original_max_position_embeddings = original_max_position_embeddings
201
+ self.extrapolation_factor = extrapolation_factor
202
+ self.attn_factor = attn_factor
203
+ self.beta_fast = beta_fast
204
+ self.beta_slow = beta_slow
205
+
206
+ self.yarn(device)
207
+
208
+ # Build here to make `torch.jit.trace` work.
209
+ self.max_seq_len_cached = max_position_embeddings
210
+ t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
211
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
212
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
213
+ emb = torch.cat((freqs, freqs), dim=-1)
214
+ dtype = torch.get_default_dtype()
215
+
216
+ self.register_buffer("cos_cached", (emb.cos() * self.mscale)[None, None, :, :].to(dtype), persistent=False)
217
+ self.register_buffer("sin_cached", (emb.sin() * self.mscale)[None, None, :, :].to(dtype), persistent=False)
218
+
219
+ def forward(self, x, seq_len=None):
220
+ # x: [bs, num_attention_heads, seq_len, head_size]
221
+ # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
222
+ if seq_len > self.max_seq_len_cached:
223
+ self.max_seq_len_cached = seq_len
224
+
225
+ t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
226
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
227
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
228
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
229
+
230
+ self.register_buffer("cos_cached", (emb.cos() * self.mscale)[None, None, :, :].to(x.dtype), persistent=False)
231
+ self.register_buffer("sin_cached", (emb.sin() * self.mscale)[None, None, :, :].to(x.dtype), persistent=False)
232
+ return (
233
+ self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
234
+ self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
235
+ )
236
+
237
+ def yarn(self, device):
238
+ pos_freqs = self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
239
+ inv_freq_extrapolation = 1.0 / pos_freqs
240
+ inv_freq_interpolation = 1.0 / (self.scale * pos_freqs)
241
+
242
+ low, high = find_correction_range(self.beta_fast, self.beta_slow, self.dim, self.base, self.original_max_position_embeddings)
243
+ inv_freq_mask = (1 - linear_ramp_mask(low, high, self.dim // 2).float().to(device)) * self.extrapolation_factor # Get n-d rotational scaling corrected for extrapolation
244
+ inv_freq = inv_freq_interpolation * (1 - inv_freq_mask) + inv_freq_extrapolation * inv_freq_mask
245
+
246
+ self.register_buffer("inv_freq", inv_freq)
247
+ self.mscale = float(get_mscale(self.scale) * self.attn_factor) # Get n-d magnitude scaling corrected for interpolation
248
+
249
+
250
+ class FuxiTranyuMLP(nn.Module):
251
+ def __init__(self, config):
252
+ super().__init__()
253
+ self.config = config
254
+ self.hidden_size = config.hidden_size
255
+ self.intermediate_size = config.intermediate_size
256
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size)
257
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size)
258
+ self.act_fn = ACT2FN[config.activation_function]
259
+
260
+ def forward(self, x):
261
+ if self.config.pretraining_tp > 1:
262
+ slice = self.intermediate_size // self.config.pretraining_tp
263
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
264
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
265
+
266
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
267
+
268
+ intermediate_states = (self.act_fn(up_proj)).split(slice, dim=2)
269
+ down_proj = [
270
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
271
+ ]
272
+ down_proj = sum(down_proj)
273
+ else:
274
+ down_proj = self.down_proj(self.act_fn(self.up_proj(x)))
275
+
276
+ return down_proj
277
+
278
+
279
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
280
+ """
281
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
282
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
283
+ """
284
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
285
+ if n_rep == 1:
286
+ return hidden_states
287
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
288
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
289
+
290
+ class FuxiTranyuAttention(nn.Module):
291
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
292
+
293
+ def __init__(self, config: FuxiTranyuConfig, layer_idx: Optional[int] = None):
294
+ super().__init__()
295
+ self.config = config
296
+ self.layer_idx = layer_idx
297
+ if layer_idx is None:
298
+ logger.warning_once(
299
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
300
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
301
+ "when creating this class."
302
+ )
303
+
304
+ self.attention_dropout = config.attention_dropout
305
+ self.hidden_size = config.hidden_size
306
+ self.num_heads = config.num_attention_heads
307
+ self.head_dim = self.hidden_size // self.num_heads
308
+ self.num_key_value_heads = config.num_key_value_heads
309
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
310
+ self.max_position_embeddings = config.max_position_embeddings
311
+ self.rope_theta = config.rope_theta
312
+ self.is_causal = True
313
+
314
+ if (self.head_dim * self.num_heads) != self.hidden_size:
315
+ raise ValueError(
316
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
317
+ f" and `num_heads`: {self.num_heads})."
318
+ )
319
+
320
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
321
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
322
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
323
+ self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=config.attention_bias)
324
+ self._init_rope()
325
+
326
+ def _init_rope(self):
327
+ if self.config.rope_scaling is None:
328
+ self.rotary_emb = FuxiTranyuRotaryEmbedding(
329
+ self.head_dim,
330
+ max_position_embeddings=self.max_position_embeddings,
331
+ base=self.rope_theta,
332
+ )
333
+ else:
334
+ scaling_type = self.config.rope_scaling["type"]
335
+ scaling_factor = self.config.rope_scaling["factor"]
336
+ if scaling_type == "linear":
337
+ self.rotary_emb = FuxiTranyuLinearScalingRotaryEmbedding(
338
+ self.head_dim,
339
+ max_position_embeddings=self.max_position_embeddings,
340
+ scaling_factor=scaling_factor,
341
+ base=self.rope_theta,
342
+ )
343
+ elif scaling_type == "dynamic":
344
+ self.rotary_emb = FuxiTranyuDynamicNTKScalingRotaryEmbedding(
345
+ self.head_dim,
346
+ max_position_embeddings=self.max_position_embeddings,
347
+ scaling_factor=scaling_factor,
348
+ base=self.rope_theta,
349
+ )
350
+ elif scaling_type == "yarn":
351
+ original_max_position_embeddings = self.config.rope_scaling["original_max_position_embeddings"]
352
+ self.rotary_emb = FuxiTranyuYaRNScaledRotaryEmbedding(
353
+ self.head_dim,
354
+ max_position_embeddings=self.max_position_embeddings,
355
+ scale=scaling_factor,
356
+ original_max_position_embeddings=original_max_position_embeddings
357
+ )
358
+ else:
359
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
360
+
361
+ def forward(
362
+ self,
363
+ hidden_states: torch.Tensor,
364
+ attention_mask: Optional[torch.Tensor] = None,
365
+ position_ids: Optional[torch.LongTensor] = None,
366
+ past_key_value: Optional[Cache] = None,
367
+ output_attentions: bool = False,
368
+ use_cache: bool = False,
369
+ cache_position: Optional[torch.LongTensor] = None,
370
+ **kwargs,
371
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
372
+ bsz, q_len, _ = hidden_states.size()
373
+
374
+ if self.config.pretraining_tp > 1:
375
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
376
+ query_slices = self.q_proj.weight.split(
377
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
378
+ )
379
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
380
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
381
+
382
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
383
+ query_states = torch.cat(query_states, dim=-1)
384
+
385
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
386
+ key_states = torch.cat(key_states, dim=-1)
387
+
388
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
389
+ value_states = torch.cat(value_states, dim=-1)
390
+
391
+ else:
392
+ query_states = self.q_proj(hidden_states)
393
+ key_states = self.k_proj(hidden_states)
394
+ value_states = self.v_proj(hidden_states)
395
+
396
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
397
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
398
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
399
+
400
+ cos, sin = self.rotary_emb(value_states, position_ids)
401
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
402
+
403
+ if past_key_value is not None:
404
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
405
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
406
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
407
+
408
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
409
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
410
+
411
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
412
+
413
+ if attention_mask is not None: # no matter the length, we just slice it
414
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
415
+ attn_weights = attn_weights + causal_mask
416
+
417
+ # upcast attention to fp32
418
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
419
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
420
+ attn_output = torch.matmul(attn_weights, value_states)
421
+
422
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
423
+ raise ValueError(
424
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
425
+ f" {attn_output.size()}"
426
+ )
427
+
428
+ attn_output = attn_output.transpose(1, 2).contiguous()
429
+
430
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
431
+
432
+ if self.config.pretraining_tp > 1:
433
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
434
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
435
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
436
+ else:
437
+ attn_output = self.o_proj(attn_output)
438
+
439
+ if not output_attentions:
440
+ attn_weights = None
441
+
442
+ return attn_output, attn_weights, past_key_value
443
+
444
+
445
+ class FuxiTranyuFlashAttention2(FuxiTranyuAttention):
446
+ """
447
+ FuxiTranyu flash attention module. This module inherits from `FuxiTranyuAttention` as the weights of the module stays
448
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
449
+ flash attention and deal with padding tokens in case the input contains any of them.
450
+ """
451
+
452
+ def __init__(self, *args, **kwargs):
453
+ super().__init__(*args, **kwargs)
454
+
455
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
456
+ # 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.
457
+ # 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).
458
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
459
+
460
+ def forward(
461
+ self,
462
+ hidden_states: torch.Tensor,
463
+ attention_mask: Optional[torch.LongTensor] = None,
464
+ position_ids: Optional[torch.LongTensor] = None,
465
+ past_key_value: Optional[Cache] = None,
466
+ output_attentions: bool = False,
467
+ use_cache: bool = False,
468
+ cache_position: Optional[torch.LongTensor] = None,
469
+ **kwargs,
470
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
471
+ if isinstance(past_key_value, StaticCache):
472
+ raise ValueError(
473
+ "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
474
+ "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
475
+ )
476
+
477
+ output_attentions = False
478
+
479
+ bsz, q_len, _ = hidden_states.size()
480
+
481
+ query_states = self.q_proj(hidden_states)
482
+ key_states = self.k_proj(hidden_states)
483
+ value_states = self.v_proj(hidden_states)
484
+
485
+ # Flash attention requires the input to have the shape
486
+ # batch_size x seq_length x head_dim x hidden_dim
487
+ # therefore we just need to keep the original shape
488
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
489
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
490
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
491
+
492
+ cos, sin = self.rotary_emb(value_states, position_ids)
493
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
494
+
495
+ if past_key_value is not None:
496
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
497
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
498
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
499
+
500
+ # 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
501
+ # to be able to avoid many of these transpose/reshape/view.
502
+ query_states = query_states.transpose(1, 2)
503
+ key_states = key_states.transpose(1, 2)
504
+ value_states = value_states.transpose(1, 2)
505
+
506
+ dropout_rate = self.attention_dropout if self.training else 0.0
507
+
508
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
509
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
510
+ # cast them back in the correct dtype just to be sure everything works as expected.
511
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
512
+ # in fp32. (FuxiTranyuRMSNorm handles it correctly)
513
+
514
+ input_dtype = query_states.dtype
515
+ if input_dtype == torch.float32:
516
+ if torch.is_autocast_enabled():
517
+ target_dtype = torch.get_autocast_gpu_dtype()
518
+ # Handle the case where the model is quantized
519
+ elif hasattr(self.config, "_pre_quantization_dtype"):
520
+ target_dtype = self.config._pre_quantization_dtype
521
+ else:
522
+ target_dtype = self.q_proj.weight.dtype
523
+
524
+ logger.warning_once(
525
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
526
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
527
+ f" {target_dtype}."
528
+ )
529
+
530
+ query_states = query_states.to(target_dtype)
531
+ key_states = key_states.to(target_dtype)
532
+ value_states = value_states.to(target_dtype)
533
+
534
+ attn_output = self._flash_attention_forward(
535
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
536
+ )
537
+
538
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
539
+ attn_output = self.o_proj(attn_output)
540
+
541
+ if not output_attentions:
542
+ attn_weights = None
543
+
544
+ return attn_output, attn_weights, past_key_value
545
+
546
+ def _flash_attention_forward(
547
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
548
+ ):
549
+ """
550
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
551
+ first unpad the input, then computes the attention scores and pad the final attention scores.
552
+
553
+ Args:
554
+ query_states (`torch.Tensor`):
555
+ Input query states to be passed to Flash Attention API
556
+ key_states (`torch.Tensor`):
557
+ Input key states to be passed to Flash Attention API
558
+ value_states (`torch.Tensor`):
559
+ Input value states to be passed to Flash Attention API
560
+ attention_mask (`torch.Tensor`):
561
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
562
+ position of padding tokens and 1 for the position of non-padding tokens.
563
+ dropout (`float`):
564
+ Attention dropout
565
+ softmax_scale (`float`, *optional*):
566
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
567
+ """
568
+ if not self._flash_attn_uses_top_left_mask:
569
+ causal = self.is_causal
570
+ else:
571
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in FuxiTranyuFlashAttention2 __init__.
572
+ causal = self.is_causal and query_length != 1
573
+
574
+ # Contains at least one padding token in the sequence
575
+ if attention_mask is not None:
576
+ batch_size = query_states.shape[0]
577
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
578
+ query_states, key_states, value_states, attention_mask, query_length
579
+ )
580
+
581
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
582
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
583
+
584
+ attn_output_unpad = flash_attn_varlen_func(
585
+ query_states,
586
+ key_states,
587
+ value_states,
588
+ cu_seqlens_q=cu_seqlens_q,
589
+ cu_seqlens_k=cu_seqlens_k,
590
+ max_seqlen_q=max_seqlen_in_batch_q,
591
+ max_seqlen_k=max_seqlen_in_batch_k,
592
+ dropout_p=dropout,
593
+ softmax_scale=softmax_scale,
594
+ causal=causal,
595
+ )
596
+
597
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
598
+ else:
599
+ attn_output = flash_attn_func(
600
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
601
+ )
602
+
603
+ return attn_output
604
+
605
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
606
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
607
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
608
+
609
+ key_layer = index_first_axis(
610
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
611
+ )
612
+ value_layer = index_first_axis(
613
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
614
+ )
615
+ if query_length == kv_seq_len:
616
+ query_layer = index_first_axis(
617
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
618
+ )
619
+ cu_seqlens_q = cu_seqlens_k
620
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
621
+ indices_q = indices_k
622
+ elif query_length == 1:
623
+ max_seqlen_in_batch_q = 1
624
+ cu_seqlens_q = torch.arange(
625
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
626
+ ) # There is a memcpy here, that is very bad.
627
+ indices_q = cu_seqlens_q[:-1]
628
+ query_layer = query_layer.squeeze(1)
629
+ else:
630
+ # The -q_len: slice assumes left padding.
631
+ attention_mask = attention_mask[:, -query_length:]
632
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
633
+
634
+ return (
635
+ query_layer,
636
+ key_layer,
637
+ value_layer,
638
+ indices_q,
639
+ (cu_seqlens_q, cu_seqlens_k),
640
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
641
+ )
642
+
643
+ class FuxiTranyuSdpaAttention(FuxiTranyuAttention):
644
+ """
645
+ FuxiTranyu attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
646
+ `FuxiTranyuAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
647
+ SDPA API.
648
+ """
649
+ def forward(
650
+ self,
651
+ hidden_states: torch.Tensor,
652
+ attention_mask: Optional[torch.Tensor] = None,
653
+ position_ids: Optional[torch.LongTensor] = None,
654
+ past_key_value: Optional[Cache] = None,
655
+ output_attentions: bool = False,
656
+ use_cache: bool = False,
657
+ cache_position: Optional[torch.LongTensor] = None,
658
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
659
+ if output_attentions:
660
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
661
+ logger.warning_once(
662
+ "FuxiTranyuModel is using FuxiTranyuSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
663
+ '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.'
664
+ )
665
+ return super().forward(
666
+ hidden_states=hidden_states,
667
+ attention_mask=attention_mask,
668
+ position_ids=position_ids,
669
+ past_key_value=past_key_value,
670
+ output_attentions=output_attentions,
671
+ use_cache=use_cache,
672
+ cache_position=cache_position,
673
+ )
674
+
675
+ bsz, q_len, _ = hidden_states.size()
676
+
677
+ query_states = self.q_proj(hidden_states)
678
+ key_states = self.k_proj(hidden_states)
679
+ value_states = self.v_proj(hidden_states)
680
+
681
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
682
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
683
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
684
+
685
+ cos, sin = self.rotary_emb(value_states, position_ids)
686
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
687
+
688
+ if past_key_value is not None:
689
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
690
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
691
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
692
+
693
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
694
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
695
+
696
+ causal_mask = attention_mask
697
+ if attention_mask is not None:
698
+ causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
699
+
700
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
701
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
702
+ if query_states.device.type == "cuda" and causal_mask is not None:
703
+ query_states = query_states.contiguous()
704
+ key_states = key_states.contiguous()
705
+ value_states = value_states.contiguous()
706
+
707
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
708
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
709
+ is_causal = True if causal_mask is None and q_len > 1 else False
710
+
711
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
712
+ query_states,
713
+ key_states,
714
+ value_states,
715
+ attn_mask=causal_mask,
716
+ dropout_p=self.attention_dropout if self.training else 0.0,
717
+ is_causal=is_causal,
718
+ )
719
+
720
+ attn_output = attn_output.transpose(1, 2).contiguous()
721
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
722
+
723
+ attn_output = self.o_proj(attn_output)
724
+
725
+ return attn_output, None, past_key_value
726
+
727
+ FUXITRANYU_ATTENTION_CLASSES = {
728
+ "eager": FuxiTranyuAttention,
729
+ "flash_attention_2": FuxiTranyuFlashAttention2,
730
+ "sdpa": FuxiTranyuSdpaAttention,
731
+ }
732
+
733
+ class FuxiTranyuDecoderLayer(nn.Module):
734
+ def __init__(self, config: FuxiTranyuConfig, layer_idx: int):
735
+ super().__init__()
736
+ self.hidden_size = config.hidden_size
737
+
738
+ self.self_attn = FUXITRANYU_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
739
+
740
+ self.mlp = FuxiTranyuMLP(config)
741
+ self.input_layernorm = FuxiTranyuRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
742
+ self.post_attention_layernorm = FuxiTranyuRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
743
+
744
+ def forward(
745
+ self,
746
+ hidden_states: torch.Tensor,
747
+ attention_mask: Optional[torch.Tensor] = None,
748
+ position_ids: Optional[torch.LongTensor] = None,
749
+ past_key_value: Optional[Cache] = None,
750
+ output_attentions: Optional[bool] = False,
751
+ use_cache: Optional[bool] = False,
752
+ cache_position: Optional[torch.LongTensor] = None,
753
+ **kwargs,
754
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
755
+ """
756
+ Args:
757
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
758
+ attention_mask (`torch.FloatTensor`, *optional*):
759
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
760
+ query_sequence_length, key_sequence_length)` if default attention is used.
761
+ output_attentions (`bool`, *optional*):
762
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
763
+ returned tensors for more detail.
764
+ use_cache (`bool`, *optional*):
765
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
766
+ (see `past_key_values`).
767
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
768
+ """
769
+ if "padding_mask" in kwargs:
770
+ warnings.warn(
771
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
772
+ )
773
+ residual = hidden_states
774
+
775
+ hidden_states = self.input_layernorm(hidden_states)
776
+
777
+ # Self Attention
778
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
779
+ hidden_states=hidden_states,
780
+ attention_mask=attention_mask,
781
+ position_ids=position_ids,
782
+ past_key_value=past_key_value,
783
+ output_attentions=output_attentions,
784
+ use_cache=use_cache,
785
+ cache_position=cache_position,
786
+ **kwargs,
787
+ )
788
+ hidden_states = residual + hidden_states
789
+
790
+ # Fully Connected
791
+ residual = hidden_states
792
+ hidden_states = self.post_attention_layernorm(hidden_states)
793
+ hidden_states = self.mlp(hidden_states)
794
+ hidden_states = residual + hidden_states
795
+
796
+ outputs = (hidden_states,)
797
+
798
+ if output_attentions:
799
+ outputs += (self_attn_weights,)
800
+
801
+ if use_cache:
802
+ outputs += (present_key_value,)
803
+
804
+ return outputs
805
+
806
+
807
+ FUXITRANYU_START_DOCSTRING = r"""
808
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
809
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
810
+ etc.)
811
+
812
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
813
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
814
+ and behavior.
815
+
816
+ Parameters:
817
+ config ([`FuxiTranyuConfig`]):
818
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
819
+ load the weights associated with the model, only the configuration. Check out the
820
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
821
+ """
822
+
823
+
824
+ @add_start_docstrings(
825
+ "The bare FuxiTranyu Model outputting raw hidden-states without any specific head on top.",
826
+ FUXITRANYU_START_DOCSTRING,
827
+ )
828
+ class FuxiTranyuPreTrainedModel(PreTrainedModel):
829
+ config_class = FuxiTranyuConfig
830
+ base_model_prefix = "model"
831
+ supports_gradient_checkpointing = True
832
+ _no_split_modules = ["FuxiTranyuDecoderLayer"]
833
+ _skip_keys_device_placement = ["past_key_values"]
834
+ _supports_flash_attn_2 = True
835
+ _supports_sdpa = True
836
+ _supports_cache_class = True
837
+
838
+ def _init_weights(self, module):
839
+ std = self.config.initializer_range
840
+ if isinstance(module, nn.Linear):
841
+ module.weight.data.normal_(mean=0.0, std=std)
842
+ if module.bias is not None:
843
+ module.bias.data.zero_()
844
+ elif isinstance(module, nn.Embedding):
845
+ module.weight.data.normal_(mean=0.0, std=std)
846
+ if module.padding_idx is not None:
847
+ module.weight.data[module.padding_idx].zero_()
848
+
849
+
850
+ FUXITRANYU_INPUTS_DOCSTRING = r"""
851
+ Args:
852
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
853
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
854
+ it.
855
+
856
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
857
+ [`PreTrainedTokenizer.__call__`] for details.
858
+
859
+ [What are input IDs?](../glossary#input-ids)
860
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
861
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
862
+
863
+ - 1 for tokens that are **not masked**,
864
+ - 0 for tokens that are **masked**.
865
+
866
+ [What are attention masks?](../glossary#attention-mask)
867
+
868
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
869
+ [`PreTrainedTokenizer.__call__`] for details.
870
+
871
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
872
+ `past_key_values`).
873
+
874
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
875
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
876
+ information on the default strategy.
877
+
878
+ - 1 indicates the head is **not masked**,
879
+ - 0 indicates the head is **masked**.
880
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
881
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
882
+ config.n_positions - 1]`.
883
+
884
+ [What are position IDs?](../glossary#position-ids)
885
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
886
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
887
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
888
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
889
+
890
+ Two formats are allowed:
891
+ - a [`~cache_utils.Cache`] instance;
892
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
893
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
894
+ cache format.
895
+
896
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
897
+ legacy cache format will be returned.
898
+
899
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
900
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
901
+ of shape `(batch_size, sequence_length)`.
902
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
903
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
904
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
905
+ model's internal embedding lookup matrix.
906
+ use_cache (`bool`, *optional*):
907
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
908
+ `past_key_values`).
909
+ output_attentions (`bool`, *optional*):
910
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
911
+ tensors for more detail.
912
+ output_hidden_states (`bool`, *optional*):
913
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
914
+ more detail.
915
+ return_dict (`bool`, *optional*):
916
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
917
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
918
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
919
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
920
+ the complete sequence length.
921
+ """
922
+
923
+
924
+ @add_start_docstrings(
925
+ "The bare FuxiTranyu Model outputting raw hidden-states without any specific head on top.",
926
+ FUXITRANYU_START_DOCSTRING,
927
+ )
928
+ class FuxiTranyuModel(FuxiTranyuPreTrainedModel):
929
+ """
930
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`FuxiTranyuDecoderLayer`]
931
+
932
+ Args:
933
+ config: FuxiTranyuConfig
934
+ """
935
+
936
+ def __init__(self, config: FuxiTranyuConfig):
937
+ super().__init__(config)
938
+ self.padding_idx = config.pad_token_id
939
+ self.vocab_size = config.vocab_size
940
+
941
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
942
+ self.layers = nn.ModuleList(
943
+ [FuxiTranyuDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
944
+ )
945
+ self.norm = FuxiTranyuRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
946
+ self.gradient_checkpointing = False
947
+
948
+ # Initialize weights and apply final processing
949
+ self.post_init()
950
+
951
+ def get_input_embeddings(self):
952
+ return self.embed_tokens
953
+
954
+ def set_input_embeddings(self, value):
955
+ self.embed_tokens = value
956
+
957
+ @add_start_docstrings_to_model_forward(FUXITRANYU_INPUTS_DOCSTRING)
958
+ def forward(
959
+ self,
960
+ input_ids: torch.LongTensor = None,
961
+ attention_mask: Optional[torch.Tensor] = None,
962
+ position_ids: Optional[torch.LongTensor] = None,
963
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
964
+ inputs_embeds: Optional[torch.FloatTensor] = None,
965
+ use_cache: Optional[bool] = None,
966
+ output_attentions: Optional[bool] = None,
967
+ output_hidden_states: Optional[bool] = None,
968
+ return_dict: Optional[bool] = None,
969
+ cache_position: Optional[torch.LongTensor] = None,
970
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
971
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
972
+ output_hidden_states = (
973
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
974
+ )
975
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
976
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
977
+
978
+ if (input_ids is None) ^ (inputs_embeds is not None):
979
+ raise ValueError(
980
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
981
+ )
982
+
983
+ if self.gradient_checkpointing and self.training and use_cache:
984
+ logger.warning_once(
985
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
986
+ )
987
+ use_cache = False
988
+
989
+ if inputs_embeds is None:
990
+ inputs_embeds = self.embed_tokens(input_ids)
991
+
992
+ return_legacy_cache = False
993
+ if use_cache and not isinstance(past_key_values, Cache): # kept for BC (non `Cache` `past_key_values` inputs)
994
+ return_legacy_cache = True
995
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
996
+ logger.warning_once(
997
+ "We detected that you are passing `past_key_values` as a tuple and this is deprecated and will be removed in v4.43. "
998
+ "Please use an appropriate `Cache` class (https://huggingface.co/docs/transformers/v4.41.3/en/internal/generation_utils#transformers.Cache)"
999
+ )
1000
+
1001
+ if cache_position is None:
1002
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1003
+ cache_position = torch.arange(
1004
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
1005
+ )
1006
+ if position_ids is None:
1007
+ position_ids = cache_position.unsqueeze(0)
1008
+
1009
+ causal_mask = self._update_causal_mask(
1010
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
1011
+ )
1012
+
1013
+ # embed positions
1014
+ hidden_states = inputs_embeds
1015
+
1016
+ # decoder layers
1017
+ all_hidden_states = () if output_hidden_states else None
1018
+ all_self_attns = () if output_attentions else None
1019
+ next_decoder_cache = None
1020
+
1021
+ for decoder_layer in self.layers:
1022
+ if output_hidden_states:
1023
+ all_hidden_states += (hidden_states,)
1024
+
1025
+ if self.gradient_checkpointing and self.training:
1026
+ layer_outputs = self._gradient_checkpointing_func(
1027
+ decoder_layer.__call__,
1028
+ hidden_states,
1029
+ causal_mask,
1030
+ position_ids,
1031
+ past_key_values,
1032
+ output_attentions,
1033
+ use_cache,
1034
+ cache_position,
1035
+ )
1036
+ else:
1037
+ layer_outputs = decoder_layer(
1038
+ hidden_states,
1039
+ attention_mask=causal_mask,
1040
+ position_ids=position_ids,
1041
+ past_key_value=past_key_values,
1042
+ output_attentions=output_attentions,
1043
+ use_cache=use_cache,
1044
+ cache_position=cache_position,
1045
+ )
1046
+
1047
+ hidden_states = layer_outputs[0]
1048
+
1049
+ if use_cache:
1050
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1051
+
1052
+ if output_attentions:
1053
+ all_self_attns += (layer_outputs[1],)
1054
+
1055
+ hidden_states = self.norm(hidden_states)
1056
+
1057
+ # add hidden states from the last decoder layer
1058
+ if output_hidden_states:
1059
+ all_hidden_states += (hidden_states,)
1060
+
1061
+ next_cache = next_decoder_cache if use_cache else None
1062
+ if return_legacy_cache:
1063
+ next_cache = next_cache.to_legacy_cache()
1064
+
1065
+ if not return_dict:
1066
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1067
+ return BaseModelOutputWithPast(
1068
+ last_hidden_state=hidden_states,
1069
+ past_key_values=next_cache,
1070
+ hidden_states=all_hidden_states,
1071
+ attentions=all_self_attns,
1072
+ )
1073
+
1074
+ def _update_causal_mask(
1075
+ self,
1076
+ attention_mask: torch.Tensor,
1077
+ input_tensor: torch.Tensor,
1078
+ cache_position: torch.Tensor,
1079
+ past_key_values: Cache,
1080
+ output_attentions: bool,
1081
+ ):
1082
+ # TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
1083
+ # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
1084
+ # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
1085
+ # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
1086
+
1087
+ if self.config._attn_implementation == "flash_attention_2":
1088
+ if attention_mask is not None and 0.0 in attention_mask:
1089
+ return attention_mask
1090
+ return None
1091
+
1092
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1093
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1094
+ # to infer the attention mask.
1095
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1096
+ using_static_cache = isinstance(past_key_values, StaticCache)
1097
+
1098
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1099
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
1100
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1101
+ attention_mask,
1102
+ inputs_embeds=input_tensor,
1103
+ past_key_values_length=past_seen_tokens,
1104
+ is_training=self.training,
1105
+ ):
1106
+ return None
1107
+
1108
+ dtype, device = input_tensor.dtype, input_tensor.device
1109
+ min_dtype = torch.finfo(dtype).min
1110
+ sequence_length = input_tensor.shape[1]
1111
+ if using_static_cache:
1112
+ target_length = past_key_values.get_max_length()
1113
+ else:
1114
+ target_length = (
1115
+ attention_mask.shape[-1]
1116
+ if isinstance(attention_mask, torch.Tensor)
1117
+ else past_seen_tokens + sequence_length + 1
1118
+ )
1119
+
1120
+ if attention_mask is not None and attention_mask.dim() == 4:
1121
+ # in this case we assume that the mask comes already in inverted form and requires no inversion or slicing
1122
+ if attention_mask.max() != 0:
1123
+ raise ValueError("Custom 4D attention mask should be passed in inverted form with max==0`")
1124
+ causal_mask = attention_mask
1125
+ else:
1126
+ causal_mask = torch.full(
1127
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
1128
+ )
1129
+ if sequence_length != 1:
1130
+ causal_mask = torch.triu(causal_mask, diagonal=1)
1131
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1132
+ causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1)
1133
+ if attention_mask is not None:
1134
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1135
+ mask_length = attention_mask.shape[-1]
1136
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
1137
+ padding_mask = padding_mask == 0
1138
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1139
+ padding_mask, min_dtype
1140
+ )
1141
+ if (
1142
+ self.config._attn_implementation == "sdpa"
1143
+ and attention_mask is not None
1144
+ and attention_mask.device.type == "cuda"
1145
+ and not output_attentions
1146
+ ):
1147
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1148
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1149
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1150
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1151
+
1152
+ return causal_mask
1153
+
1154
+
1155
+ class FuxiTranyuForCausalLM(FuxiTranyuPreTrainedModel):
1156
+ _tied_weights_keys = ["lm_head.weight"]
1157
+
1158
+ def __init__(self, config):
1159
+ super().__init__(config)
1160
+ self.model = FuxiTranyuModel(config)
1161
+ self.vocab_size = config.vocab_size
1162
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1163
+
1164
+ # Initialize weights and apply final processing
1165
+ self.post_init()
1166
+
1167
+ def get_input_embeddings(self):
1168
+ return self.model.embed_tokens
1169
+
1170
+ def set_input_embeddings(self, value):
1171
+ self.model.embed_tokens = value
1172
+
1173
+ def get_output_embeddings(self):
1174
+ return self.lm_head
1175
+
1176
+ def set_output_embeddings(self, new_embeddings):
1177
+ self.lm_head = new_embeddings
1178
+
1179
+ def set_decoder(self, decoder):
1180
+ self.model = decoder
1181
+
1182
+ def get_decoder(self):
1183
+ return self.model
1184
+
1185
+ @add_start_docstrings_to_model_forward(FUXITRANYU_INPUTS_DOCSTRING)
1186
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1187
+ def forward(
1188
+ self,
1189
+ input_ids: torch.LongTensor = None,
1190
+ attention_mask: Optional[torch.Tensor] = None,
1191
+ position_ids: Optional[torch.LongTensor] = None,
1192
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1193
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1194
+ labels: Optional[torch.LongTensor] = None,
1195
+ use_cache: Optional[bool] = None,
1196
+ output_attentions: Optional[bool] = None,
1197
+ output_hidden_states: Optional[bool] = None,
1198
+ return_dict: Optional[bool] = None,
1199
+ cache_position: Optional[torch.LongTensor] = None,
1200
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1201
+ r"""
1202
+ Args:
1203
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1204
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1205
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1206
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1207
+
1208
+ Returns:
1209
+
1210
+ Example:
1211
+
1212
+ ```python
1213
+ >>> from transformers import AutoTokenizer, FuxiTranyuForCausalLM
1214
+
1215
+ >>> model = FuxiTranyuForCausalLM.from_pretrained("meta-FuxiTranyu/FuxiTranyu-2-7b-hf")
1216
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-FuxiTranyu/FuxiTranyu-2-7b-hf")
1217
+
1218
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1219
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1220
+
1221
+ >>> # Generate
1222
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1223
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1224
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1225
+ ```"""
1226
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1227
+ output_hidden_states = (
1228
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1229
+ )
1230
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1231
+
1232
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1233
+ outputs = self.model(
1234
+ input_ids=input_ids,
1235
+ attention_mask=attention_mask,
1236
+ position_ids=position_ids,
1237
+ past_key_values=past_key_values,
1238
+ inputs_embeds=inputs_embeds,
1239
+ use_cache=use_cache,
1240
+ output_attentions=output_attentions,
1241
+ output_hidden_states=output_hidden_states,
1242
+ return_dict=return_dict,
1243
+ cache_position=cache_position,
1244
+ )
1245
+
1246
+ hidden_states = outputs[0]
1247
+ if self.config.pretraining_tp > 1:
1248
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1249
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1250
+ logits = torch.cat(logits, dim=-1)
1251
+ else:
1252
+ logits = self.lm_head(hidden_states)
1253
+ logits = logits.float()
1254
+
1255
+ loss = None
1256
+ if labels is not None:
1257
+ # Shift so that tokens < n predict n
1258
+ shift_logits = logits[..., :-1, :].contiguous()
1259
+ shift_labels = labels[..., 1:].contiguous()
1260
+ # Flatten the tokens
1261
+ loss_fct = CrossEntropyLoss()
1262
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1263
+ shift_labels = shift_labels.view(-1)
1264
+ # Enable model parallelism
1265
+ shift_labels = shift_labels.to(shift_logits.device)
1266
+ loss = loss_fct(shift_logits, shift_labels)
1267
+
1268
+ if not return_dict:
1269
+ output = (logits,) + outputs[1:]
1270
+ return (loss,) + output if loss is not None else output
1271
+
1272
+ return CausalLMOutputWithPast(
1273
+ loss=loss,
1274
+ logits=logits,
1275
+ past_key_values=outputs.past_key_values,
1276
+ hidden_states=outputs.hidden_states,
1277
+ attentions=outputs.attentions,
1278
+ )
1279
+
1280
+ def prepare_inputs_for_generation(
1281
+ self,
1282
+ input_ids,
1283
+ past_key_values=None,
1284
+ attention_mask=None,
1285
+ inputs_embeds=None,
1286
+ cache_position=None,
1287
+ use_cache=True,
1288
+ **kwargs,
1289
+ ):
1290
+ past_length = 0
1291
+ if past_key_values is not None:
1292
+ # Past key values are always initialized with a `Cache` object -> no need for if-else anymore
1293
+ past_length = cache_position[0] if cache_position is not None else past_key_values.get_seq_length()
1294
+ max_cache_length = (
1295
+ torch.tensor(past_key_values.get_max_length(), device=input_ids.device)
1296
+ if past_key_values.get_max_length() is not None
1297
+ else None
1298
+ )
1299
+ cache_length = past_length if max_cache_length is None else torch.min(max_cache_length, past_length)
1300
+
1301
+ # Keep only the unprocessed tokens:
1302
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1303
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as input)
1304
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1305
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1306
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1307
+ # input_ids based on the past_length.
1308
+ elif past_length < input_ids.shape[1]:
1309
+ input_ids = input_ids[:, past_length:]
1310
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1311
+
1312
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1313
+ if (
1314
+ max_cache_length is not None
1315
+ and attention_mask is not None
1316
+ and cache_length + input_ids.shape[1] > max_cache_length
1317
+ ):
1318
+ attention_mask = attention_mask[:, -max_cache_length:]
1319
+
1320
+ position_ids = kwargs.get("position_ids", None)
1321
+ if attention_mask is not None and position_ids is None:
1322
+ # create position_ids on the fly for batch generation
1323
+ position_ids = attention_mask.long().cumsum(-1) - 1
1324
+ position_ids.masked_fill_(attention_mask == 0, 1)
1325
+ if past_key_values:
1326
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1327
+
1328
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1329
+ if inputs_embeds is not None and past_length == 0:
1330
+ model_inputs = {"inputs_embeds": inputs_embeds}
1331
+ else:
1332
+ # The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
1333
+ # recompiles graphs as the stride of the inputs is a guard. Ref: https://github.com/huggingface/transformers/pull/29114
1334
+ # TODO: use `next_tokens` directly instead.
1335
+ model_inputs = {"input_ids": input_ids.contiguous()}
1336
+
1337
+ input_length = position_ids.shape[-1] if position_ids is not None else input_ids.shape[-1]
1338
+ if cache_position is None:
1339
+ cache_position = torch.arange(past_length, past_length + input_length, device=input_ids.device)
1340
+ elif use_cache:
1341
+ cache_position = cache_position[-input_length:]
1342
+
1343
+ model_inputs.update(
1344
+ {
1345
+ "position_ids": position_ids,
1346
+ "cache_position": cache_position,
1347
+ "past_key_values": past_key_values,
1348
+ "use_cache": use_cache,
1349
+ "attention_mask": attention_mask,
1350
+ }
1351
+ )
1352
+ return model_inputs
1353
+
1354
+ @staticmethod
1355
+ def _reorder_cache(past_key_values, beam_idx):
1356
+ reordered_past = ()
1357
+ for layer_past in past_key_values:
1358
+ reordered_past += (
1359
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1360
+ )
1361
+ return reordered_past
1362
+
1363
+
1364
+ @add_start_docstrings(
1365
+ """
1366
+ The FuxiTranyu Model transformer with a sequence classification head on top (linear layer).
1367
+
1368
+ [`FuxiTranyuForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1369
+ (e.g. GPT-2) do.
1370
+
1371
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1372
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1373
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1374
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1375
+ each row of the batch).
1376
+ """,
1377
+ FUXITRANYU_START_DOCSTRING,
1378
+ )
1379
+ class FuxiTranyuForSequenceClassification(FuxiTranyuPreTrainedModel):
1380
+ def __init__(self, config):
1381
+ super().__init__(config)
1382
+ self.num_labels = config.num_labels
1383
+ self.model = FuxiTranyuModel(config)
1384
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1385
+
1386
+ # Initialize weights and apply final processing
1387
+ self.post_init()
1388
+
1389
+ def get_input_embeddings(self):
1390
+ return self.model.embed_tokens
1391
+
1392
+ def set_input_embeddings(self, value):
1393
+ self.model.embed_tokens = value
1394
+
1395
+ @add_start_docstrings_to_model_forward(FUXITRANYU_INPUTS_DOCSTRING)
1396
+ def forward(
1397
+ self,
1398
+ input_ids: torch.LongTensor = None,
1399
+ attention_mask: Optional[torch.Tensor] = None,
1400
+ position_ids: Optional[torch.LongTensor] = None,
1401
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1402
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1403
+ labels: Optional[torch.LongTensor] = None,
1404
+ use_cache: Optional[bool] = None,
1405
+ output_attentions: Optional[bool] = None,
1406
+ output_hidden_states: Optional[bool] = None,
1407
+ return_dict: Optional[bool] = None,
1408
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1409
+ r"""
1410
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1411
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1412
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1413
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1414
+ """
1415
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1416
+
1417
+ transformer_outputs = self.model(
1418
+ input_ids,
1419
+ attention_mask=attention_mask,
1420
+ position_ids=position_ids,
1421
+ past_key_values=past_key_values,
1422
+ inputs_embeds=inputs_embeds,
1423
+ use_cache=use_cache,
1424
+ output_attentions=output_attentions,
1425
+ output_hidden_states=output_hidden_states,
1426
+ return_dict=return_dict,
1427
+ )
1428
+ hidden_states = transformer_outputs[0]
1429
+ logits = self.score(hidden_states)
1430
+
1431
+ if input_ids is not None:
1432
+ batch_size = input_ids.shape[0]
1433
+ else:
1434
+ batch_size = inputs_embeds.shape[0]
1435
+
1436
+ if self.config.pad_token_id is None and batch_size != 1:
1437
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1438
+ if self.config.pad_token_id is None:
1439
+ sequence_lengths = -1
1440
+ else:
1441
+ if input_ids is not None:
1442
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1443
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1444
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1445
+ sequence_lengths = sequence_lengths.to(logits.device)
1446
+ else:
1447
+ sequence_lengths = -1
1448
+
1449
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1450
+
1451
+ loss = None
1452
+ if labels is not None:
1453
+ labels = labels.to(logits.device)
1454
+ if self.config.problem_type is None:
1455
+ if self.num_labels == 1:
1456
+ self.config.problem_type = "regression"
1457
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1458
+ self.config.problem_type = "single_label_classification"
1459
+ else:
1460
+ self.config.problem_type = "multi_label_classification"
1461
+
1462
+ if self.config.problem_type == "regression":
1463
+ loss_fct = MSELoss()
1464
+ if self.num_labels == 1:
1465
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1466
+ else:
1467
+ loss = loss_fct(pooled_logits, labels)
1468
+ elif self.config.problem_type == "single_label_classification":
1469
+ loss_fct = CrossEntropyLoss()
1470
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1471
+ elif self.config.problem_type == "multi_label_classification":
1472
+ loss_fct = BCEWithLogitsLoss()
1473
+ loss = loss_fct(pooled_logits, labels)
1474
+ if not return_dict:
1475
+ output = (pooled_logits,) + transformer_outputs[1:]
1476
+ return ((loss,) + output) if loss is not None else output
1477
+
1478
+ return SequenceClassifierOutputWithPast(
1479
+ loss=loss,
1480
+ logits=pooled_logits,
1481
+ past_key_values=transformer_outputs.past_key_values,
1482
+ hidden_states=transformer_outputs.hidden_states,
1483
+ attentions=transformer_outputs.attentions,
1484
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>"
5
+ ],
6
+ "bos_token": {
7
+ "content": "<|im_start|>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false
12
+ },
13
+ "eos_token": {
14
+ "content": "<|im_end|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false
19
+ },
20
+ "pad_token": {
21
+ "content": "<|im_end|>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false
26
+ },
27
+ "unk_token": {
28
+ "content": "<|endoftext|>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false
33
+ }
34
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e5a3a69fb7de0056112378b7d713cc36144346a600394817bac23dcdac624911
3
+ size 13945373
tokenizer_config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "0": {
5
+ "content": "<|endoftext|>",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "250680": {
13
+ "content": "<|im_start|>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ },
20
+ "250681": {
21
+ "content": "<|im_end|>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": true
27
+ }
28
+ },
29
+ "additional_special_tokens": [
30
+ "<|im_start|>",
31
+ "<|im_end|>"
32
+ ],
33
+ "bos_token": "<|im_start|>",
34
+ "chat_template": "{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}",
35
+ "clean_up_tokenization_spaces": true,
36
+ "eos_token": "<|im_end|>",
37
+ "model_max_length": 1024,
38
+ "pad_token": "<|im_end|>",
39
+ "tokenizer_class": "GPT2Tokenizer",
40
+ "unk_token": "<|endoftext|>"
41
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff