mrfakename commited on
Commit
712bcbf
·
verified ·
1 Parent(s): f61fede

Upload folder using huggingface_hub

Browse files
config.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "MoonshotForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_moonshot.MoonshotConfig",
8
+ "AutoModel": "modeling_moonshot.MoonshotModel",
9
+ "AutoModelForCausalLM": "modeling_moonshot.MoonshotForCausalLM"
10
+ },
11
+ "bos_token_id": 1,
12
+ "eos_token_id": 2,
13
+ "hidden_act": "silu",
14
+ "hidden_size": 3072,
15
+ "initializer_range": 0.02,
16
+ "intermediate_size": 8192,
17
+ "model_type": "moonshot",
18
+ "num_attention_heads": 24,
19
+ "num_hidden_layers": 16,
20
+ "num_key_value_heads": 8,
21
+ "pad_token_id": 0,
22
+ "pretraining_sequence_length": 40000,
23
+ "rms_norm_eps": 1e-05,
24
+ "rope_scaling": {
25
+ "factor": 16.0,
26
+ "type": "linear"
27
+ },
28
+ "rope_theta": 500000.0,
29
+ "tie_word_embeddings": false,
30
+ "torch_dtype": "bfloat16",
31
+ "transformers_version": "4.46.1",
32
+ "use_cache": true,
33
+ "vocab_size": 172032
34
+ }
configuration_moonshot.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers.configuration_utils import PretrainedConfig
2
+
3
+
4
+ class MoonshotConfig(PretrainedConfig):
5
+ r"""
6
+ This is the configuration class to store the configuration of a [`MoonshotModel`].
7
+ It is used to instantiate an Moonshot model according to the specified arguments, defining the model
8
+ architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of
9
+ the MSH-L architecture.
10
+
11
+ Configuration objects inherit from [`PretrainedConfig`] and can be used
12
+ to control the model outputs. Read the documentation from [`PretrainedConfig`]
13
+ for more information.
14
+
15
+
16
+ Args:
17
+ vocab_size (`int`, *optional*, defaults to 32000):
18
+ Vocabulary size of the Moonshot model. Defines the number of different tokens that can be represented by the
19
+ `inputs_ids` passed when calling [`MoonshotModel`]
20
+ hidden_size (`int`, *optional*, defaults to 4096):
21
+ Dimension of the hidden representations.
22
+ intermediate_size (`int`, *optional*, defaults to 11008):
23
+ Dimension of the MLP representations.
24
+ num_hidden_layers (`int`, *optional*, defaults to 32):
25
+ Number of hidden layers in the Transformer encoder.
26
+ num_attention_heads (`int`, *optional*, defaults to 32):
27
+ Number of attention heads for each attention layer in the Transformer encoder.
28
+ num_key_value_heads (`int`, *optional*):
29
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
30
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
31
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
32
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
33
+ by meanpooling all the original heads within that group. For more details checkout [this
34
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
35
+ `num_attention_heads`.
36
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
37
+ The non-linear activation function (function or string) in the decoder.
38
+ pretraining_sequence_length (`int`, *optional*, defaults to 4096):
39
+ The sequence length that this model was trained with
40
+ initializer_range (`float`, *optional*, defaults to 0.02):
41
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
42
+ rms_norm_eps (`float`, *optional*, defaults to 1e-12):
43
+ The epsilon used by the rms normalization layers.
44
+ use_cache (`bool`, *optional*, defaults to `True`):
45
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
46
+ relevant if `config.is_decoder=True`.
47
+ rope_scaling (`Dict`, *optional*):
48
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports three scaling
49
+ strategies: linear and dynamic. Their scaling factor must be an float greater than 1. The expected format
50
+ is `{"type": strategy name, "factor": scaling factor}`
51
+ these scaling strategies behave:
52
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
53
+ experimental feature, subject to breaking API changes in future versions.
54
+ Example:
55
+
56
+ ```python
57
+ >>> from configuration_moonshot import MoonshotConfig
58
+
59
+ >>> # Initializing a MSH-L style configuration
60
+ >>> configuration = MoonshotConfig()
61
+ ```
62
+ """
63
+ model_type = "moonshot"
64
+ keys_to_ignore_at_inference = ["past_key_values"]
65
+
66
+ def __init__(
67
+ self,
68
+ vocab_size=163840,
69
+ hidden_size=4096,
70
+ intermediate_size=11008,
71
+ num_hidden_layers=32,
72
+ num_attention_heads=32,
73
+ num_key_value_heads=None,
74
+ hidden_act="silu",
75
+ pretraining_sequence_length=4096,
76
+ initializer_range=0.02,
77
+ rms_norm_eps=1e-6,
78
+ use_cache=True,
79
+ pad_token_id=0,
80
+ bos_token_id=1,
81
+ eos_token_id=2,
82
+ rope_theta=10000.0,
83
+ rope_scaling=None,
84
+ attention_bias=False,
85
+ tie_word_embeddings=False,
86
+ attention_qknorm: dict = None, #{'type': 'tensor'/ 'head'}
87
+ **kwargs,
88
+ ):
89
+ self.vocab_size = vocab_size
90
+ self.pretraining_sequence_length = pretraining_sequence_length
91
+ self.hidden_size = hidden_size
92
+ self.intermediate_size = intermediate_size
93
+ self.num_hidden_layers = num_hidden_layers
94
+ self.num_attention_heads = num_attention_heads
95
+
96
+ # for backward compatibility
97
+ if num_key_value_heads is None:
98
+ num_key_value_heads = num_attention_heads
99
+
100
+ self.num_key_value_heads = num_key_value_heads
101
+ self.hidden_act = hidden_act
102
+ self.initializer_range = initializer_range
103
+ self.rms_norm_eps = rms_norm_eps
104
+ self.use_cache = use_cache
105
+ self.rope_theta = rope_theta
106
+ self.rope_scaling = rope_scaling
107
+ self._rope_scaling_validation()
108
+ self.attention_bias = attention_bias
109
+ self.attention_qknorm = attention_qknorm
110
+
111
+
112
+ super().__init__(
113
+ pad_token_id=pad_token_id,
114
+ bos_token_id=bos_token_id,
115
+ eos_token_id=eos_token_id,
116
+ tie_word_embeddings=tie_word_embeddings,
117
+ **kwargs,
118
+ )
119
+
120
+ def _rope_scaling_validation(self):
121
+ """
122
+ Validate the `rope_scaling` configuration.
123
+ """
124
+ if self.rope_scaling is None:
125
+ return
126
+
127
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
128
+ raise ValueError(
129
+ "`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, "
130
+ f"got {self.rope_scaling}"
131
+ )
132
+ rope_scaling_type = self.rope_scaling.get("type", None)
133
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
134
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
135
+ raise ValueError(
136
+ f"`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
137
+ )
138
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
139
+ raise ValueError(f"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}")
generation_config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "max_length": 40000
3
+ }
model-1-of-17.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6ed0c5f9127d15c51e7177a1194224b5a60524252c0e8177d24b776aa956d742
3
+ size 201340168
model-10-of-17.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:56a52ad6e003e63e3c4dee7e42928722205699f4ef1e057219709ddf2978ae9b
3
+ size 201340168
model-11-of-17.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:21b1a797f70efc3dfbe4ee5d990b1a8af3e9874dab54f5d9957dc4f266a1f053
3
+ size 201340176
model-12-of-17.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0f69ac09383bd9035fd6917f77e799f4829e5f065d4cd8179888b90108701fbc
3
+ size 201340176
model-13-of-17.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0df9fdc950c2cb2b0bde8494423489ec11acd2ec553563948bc4d36ee2ffff0c
3
+ size 201340176
model-14-of-17.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:595a49d1027d7678ed284e1f9f2e13d32a927319b6c521e840df8680105f92ba
3
+ size 201340176
model-15-of-17.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5b179ed2aae1a34545207643fff217386aaf78124c5f452d8c00ab3fcc6ab6ed
3
+ size 201340176
model-16-of-17.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:32088fbcf3264b2d3da4982e932d7e7f476eaa36549cc9c65c303e2db9840364
3
+ size 201340176
model-17-of-17.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8b3bb0b7d3161e8cd226f072d0922b69c7d54d8456d7ba3b07218ecba473b575
3
+ size 2113935688
model-2-of-17.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8f8627c5582e0c6a905233ec04ac078e92055203405ced5414092a023c73db94
3
+ size 201340168
model-3-of-17.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:46383685639db3ad3659731f7d5689c3c8755b0adf74e10ac80021b2592dc8c3
3
+ size 201340168
model-4-of-17.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:05eae55f6f1b3d1b5c07bd698f0d72de5568f0617e91f2efbfdafff897dde552
3
+ size 201340168
model-5-of-17.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f719c350c7bf50fbbc5cd8c682c04508dacf3f1fa123701319a03b3d092f797c
3
+ size 201340168
model-6-of-17.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e3147adcec3fead667f48128fe21f48ce00700c588e013a5a90069a412fea148
3
+ size 201340168
model-7-of-17.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fd7ee54d8a9b550871004a60c8dcd1373aa0e2c19b3c49c59844dcc868056bcd
3
+ size 201340168
model-8-of-17.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5c0dce98e6be48e7be70f13bbc5f9cef5bba1396732ff2d9325e3eb359c55bcb
3
+ size 201340168
model-9-of-17.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:537ede5431bc970fa75507ff25ff6d1b52fc45bb8a07e0e6d59001669bc96000
3
+ size 201340168
model.safetensors.index.json ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 5335359488
4
+ },
5
+ "weight_map": {
6
+ "model.layers.0.self_attn.q_proj.weight": "model-1-of-17.safetensors",
7
+ "model.layers.0.self_attn.k_proj.weight": "model-1-of-17.safetensors",
8
+ "model.layers.0.self_attn.v_proj.weight": "model-1-of-17.safetensors",
9
+ "model.layers.0.self_attn.o_proj.weight": "model-1-of-17.safetensors",
10
+ "model.layers.0.input_layernorm.weight": "model-1-of-17.safetensors",
11
+ "model.layers.0.post_attention_layernorm.weight": "model-1-of-17.safetensors",
12
+ "model.layers.0.mlp.gate_proj.weight": "model-1-of-17.safetensors",
13
+ "model.layers.0.mlp.down_proj.weight": "model-1-of-17.safetensors",
14
+ "model.layers.0.mlp.up_proj.weight": "model-1-of-17.safetensors",
15
+ "model.layers.0.self_attn.rotary_emb.inv_freq": "model-1-of-17.safetensors",
16
+ "model.layers.1.self_attn.q_proj.weight": "model-2-of-17.safetensors",
17
+ "model.layers.1.self_attn.k_proj.weight": "model-2-of-17.safetensors",
18
+ "model.layers.1.self_attn.v_proj.weight": "model-2-of-17.safetensors",
19
+ "model.layers.1.self_attn.o_proj.weight": "model-2-of-17.safetensors",
20
+ "model.layers.1.input_layernorm.weight": "model-2-of-17.safetensors",
21
+ "model.layers.1.post_attention_layernorm.weight": "model-2-of-17.safetensors",
22
+ "model.layers.1.mlp.gate_proj.weight": "model-2-of-17.safetensors",
23
+ "model.layers.1.mlp.down_proj.weight": "model-2-of-17.safetensors",
24
+ "model.layers.1.mlp.up_proj.weight": "model-2-of-17.safetensors",
25
+ "model.layers.1.self_attn.rotary_emb.inv_freq": "model-2-of-17.safetensors",
26
+ "model.layers.2.self_attn.q_proj.weight": "model-3-of-17.safetensors",
27
+ "model.layers.2.self_attn.k_proj.weight": "model-3-of-17.safetensors",
28
+ "model.layers.2.self_attn.v_proj.weight": "model-3-of-17.safetensors",
29
+ "model.layers.2.self_attn.o_proj.weight": "model-3-of-17.safetensors",
30
+ "model.layers.2.input_layernorm.weight": "model-3-of-17.safetensors",
31
+ "model.layers.2.post_attention_layernorm.weight": "model-3-of-17.safetensors",
32
+ "model.layers.2.mlp.gate_proj.weight": "model-3-of-17.safetensors",
33
+ "model.layers.2.mlp.down_proj.weight": "model-3-of-17.safetensors",
34
+ "model.layers.2.mlp.up_proj.weight": "model-3-of-17.safetensors",
35
+ "model.layers.2.self_attn.rotary_emb.inv_freq": "model-3-of-17.safetensors",
36
+ "model.layers.3.self_attn.q_proj.weight": "model-4-of-17.safetensors",
37
+ "model.layers.3.self_attn.k_proj.weight": "model-4-of-17.safetensors",
38
+ "model.layers.3.self_attn.v_proj.weight": "model-4-of-17.safetensors",
39
+ "model.layers.3.self_attn.o_proj.weight": "model-4-of-17.safetensors",
40
+ "model.layers.3.input_layernorm.weight": "model-4-of-17.safetensors",
41
+ "model.layers.3.post_attention_layernorm.weight": "model-4-of-17.safetensors",
42
+ "model.layers.3.mlp.gate_proj.weight": "model-4-of-17.safetensors",
43
+ "model.layers.3.mlp.down_proj.weight": "model-4-of-17.safetensors",
44
+ "model.layers.3.mlp.up_proj.weight": "model-4-of-17.safetensors",
45
+ "model.layers.3.self_attn.rotary_emb.inv_freq": "model-4-of-17.safetensors",
46
+ "model.layers.4.self_attn.q_proj.weight": "model-5-of-17.safetensors",
47
+ "model.layers.4.self_attn.k_proj.weight": "model-5-of-17.safetensors",
48
+ "model.layers.4.self_attn.v_proj.weight": "model-5-of-17.safetensors",
49
+ "model.layers.4.self_attn.o_proj.weight": "model-5-of-17.safetensors",
50
+ "model.layers.4.input_layernorm.weight": "model-5-of-17.safetensors",
51
+ "model.layers.4.post_attention_layernorm.weight": "model-5-of-17.safetensors",
52
+ "model.layers.4.mlp.gate_proj.weight": "model-5-of-17.safetensors",
53
+ "model.layers.4.mlp.down_proj.weight": "model-5-of-17.safetensors",
54
+ "model.layers.4.mlp.up_proj.weight": "model-5-of-17.safetensors",
55
+ "model.layers.4.self_attn.rotary_emb.inv_freq": "model-5-of-17.safetensors",
56
+ "model.layers.5.self_attn.q_proj.weight": "model-6-of-17.safetensors",
57
+ "model.layers.5.self_attn.k_proj.weight": "model-6-of-17.safetensors",
58
+ "model.layers.5.self_attn.v_proj.weight": "model-6-of-17.safetensors",
59
+ "model.layers.5.self_attn.o_proj.weight": "model-6-of-17.safetensors",
60
+ "model.layers.5.input_layernorm.weight": "model-6-of-17.safetensors",
61
+ "model.layers.5.post_attention_layernorm.weight": "model-6-of-17.safetensors",
62
+ "model.layers.5.mlp.gate_proj.weight": "model-6-of-17.safetensors",
63
+ "model.layers.5.mlp.down_proj.weight": "model-6-of-17.safetensors",
64
+ "model.layers.5.mlp.up_proj.weight": "model-6-of-17.safetensors",
65
+ "model.layers.5.self_attn.rotary_emb.inv_freq": "model-6-of-17.safetensors",
66
+ "model.layers.6.self_attn.q_proj.weight": "model-7-of-17.safetensors",
67
+ "model.layers.6.self_attn.k_proj.weight": "model-7-of-17.safetensors",
68
+ "model.layers.6.self_attn.v_proj.weight": "model-7-of-17.safetensors",
69
+ "model.layers.6.self_attn.o_proj.weight": "model-7-of-17.safetensors",
70
+ "model.layers.6.input_layernorm.weight": "model-7-of-17.safetensors",
71
+ "model.layers.6.post_attention_layernorm.weight": "model-7-of-17.safetensors",
72
+ "model.layers.6.mlp.gate_proj.weight": "model-7-of-17.safetensors",
73
+ "model.layers.6.mlp.down_proj.weight": "model-7-of-17.safetensors",
74
+ "model.layers.6.mlp.up_proj.weight": "model-7-of-17.safetensors",
75
+ "model.layers.6.self_attn.rotary_emb.inv_freq": "model-7-of-17.safetensors",
76
+ "model.layers.7.self_attn.q_proj.weight": "model-8-of-17.safetensors",
77
+ "model.layers.7.self_attn.k_proj.weight": "model-8-of-17.safetensors",
78
+ "model.layers.7.self_attn.v_proj.weight": "model-8-of-17.safetensors",
79
+ "model.layers.7.self_attn.o_proj.weight": "model-8-of-17.safetensors",
80
+ "model.layers.7.input_layernorm.weight": "model-8-of-17.safetensors",
81
+ "model.layers.7.post_attention_layernorm.weight": "model-8-of-17.safetensors",
82
+ "model.layers.7.mlp.gate_proj.weight": "model-8-of-17.safetensors",
83
+ "model.layers.7.mlp.down_proj.weight": "model-8-of-17.safetensors",
84
+ "model.layers.7.mlp.up_proj.weight": "model-8-of-17.safetensors",
85
+ "model.layers.7.self_attn.rotary_emb.inv_freq": "model-8-of-17.safetensors",
86
+ "model.layers.8.self_attn.q_proj.weight": "model-9-of-17.safetensors",
87
+ "model.layers.8.self_attn.k_proj.weight": "model-9-of-17.safetensors",
88
+ "model.layers.8.self_attn.v_proj.weight": "model-9-of-17.safetensors",
89
+ "model.layers.8.self_attn.o_proj.weight": "model-9-of-17.safetensors",
90
+ "model.layers.8.input_layernorm.weight": "model-9-of-17.safetensors",
91
+ "model.layers.8.post_attention_layernorm.weight": "model-9-of-17.safetensors",
92
+ "model.layers.8.mlp.gate_proj.weight": "model-9-of-17.safetensors",
93
+ "model.layers.8.mlp.down_proj.weight": "model-9-of-17.safetensors",
94
+ "model.layers.8.mlp.up_proj.weight": "model-9-of-17.safetensors",
95
+ "model.layers.8.self_attn.rotary_emb.inv_freq": "model-9-of-17.safetensors",
96
+ "model.layers.9.self_attn.q_proj.weight": "model-10-of-17.safetensors",
97
+ "model.layers.9.self_attn.k_proj.weight": "model-10-of-17.safetensors",
98
+ "model.layers.9.self_attn.v_proj.weight": "model-10-of-17.safetensors",
99
+ "model.layers.9.self_attn.o_proj.weight": "model-10-of-17.safetensors",
100
+ "model.layers.9.input_layernorm.weight": "model-10-of-17.safetensors",
101
+ "model.layers.9.post_attention_layernorm.weight": "model-10-of-17.safetensors",
102
+ "model.layers.9.mlp.gate_proj.weight": "model-10-of-17.safetensors",
103
+ "model.layers.9.mlp.down_proj.weight": "model-10-of-17.safetensors",
104
+ "model.layers.9.mlp.up_proj.weight": "model-10-of-17.safetensors",
105
+ "model.layers.9.self_attn.rotary_emb.inv_freq": "model-10-of-17.safetensors",
106
+ "model.layers.10.self_attn.q_proj.weight": "model-11-of-17.safetensors",
107
+ "model.layers.10.self_attn.k_proj.weight": "model-11-of-17.safetensors",
108
+ "model.layers.10.self_attn.v_proj.weight": "model-11-of-17.safetensors",
109
+ "model.layers.10.self_attn.o_proj.weight": "model-11-of-17.safetensors",
110
+ "model.layers.10.input_layernorm.weight": "model-11-of-17.safetensors",
111
+ "model.layers.10.post_attention_layernorm.weight": "model-11-of-17.safetensors",
112
+ "model.layers.10.mlp.gate_proj.weight": "model-11-of-17.safetensors",
113
+ "model.layers.10.mlp.down_proj.weight": "model-11-of-17.safetensors",
114
+ "model.layers.10.mlp.up_proj.weight": "model-11-of-17.safetensors",
115
+ "model.layers.10.self_attn.rotary_emb.inv_freq": "model-11-of-17.safetensors",
116
+ "model.layers.11.self_attn.q_proj.weight": "model-12-of-17.safetensors",
117
+ "model.layers.11.self_attn.k_proj.weight": "model-12-of-17.safetensors",
118
+ "model.layers.11.self_attn.v_proj.weight": "model-12-of-17.safetensors",
119
+ "model.layers.11.self_attn.o_proj.weight": "model-12-of-17.safetensors",
120
+ "model.layers.11.input_layernorm.weight": "model-12-of-17.safetensors",
121
+ "model.layers.11.post_attention_layernorm.weight": "model-12-of-17.safetensors",
122
+ "model.layers.11.mlp.gate_proj.weight": "model-12-of-17.safetensors",
123
+ "model.layers.11.mlp.down_proj.weight": "model-12-of-17.safetensors",
124
+ "model.layers.11.mlp.up_proj.weight": "model-12-of-17.safetensors",
125
+ "model.layers.11.self_attn.rotary_emb.inv_freq": "model-12-of-17.safetensors",
126
+ "model.layers.12.self_attn.q_proj.weight": "model-13-of-17.safetensors",
127
+ "model.layers.12.self_attn.k_proj.weight": "model-13-of-17.safetensors",
128
+ "model.layers.12.self_attn.v_proj.weight": "model-13-of-17.safetensors",
129
+ "model.layers.12.self_attn.o_proj.weight": "model-13-of-17.safetensors",
130
+ "model.layers.12.input_layernorm.weight": "model-13-of-17.safetensors",
131
+ "model.layers.12.post_attention_layernorm.weight": "model-13-of-17.safetensors",
132
+ "model.layers.12.mlp.gate_proj.weight": "model-13-of-17.safetensors",
133
+ "model.layers.12.mlp.down_proj.weight": "model-13-of-17.safetensors",
134
+ "model.layers.12.mlp.up_proj.weight": "model-13-of-17.safetensors",
135
+ "model.layers.12.self_attn.rotary_emb.inv_freq": "model-13-of-17.safetensors",
136
+ "model.layers.13.self_attn.q_proj.weight": "model-14-of-17.safetensors",
137
+ "model.layers.13.self_attn.k_proj.weight": "model-14-of-17.safetensors",
138
+ "model.layers.13.self_attn.v_proj.weight": "model-14-of-17.safetensors",
139
+ "model.layers.13.self_attn.o_proj.weight": "model-14-of-17.safetensors",
140
+ "model.layers.13.input_layernorm.weight": "model-14-of-17.safetensors",
141
+ "model.layers.13.post_attention_layernorm.weight": "model-14-of-17.safetensors",
142
+ "model.layers.13.mlp.gate_proj.weight": "model-14-of-17.safetensors",
143
+ "model.layers.13.mlp.down_proj.weight": "model-14-of-17.safetensors",
144
+ "model.layers.13.mlp.up_proj.weight": "model-14-of-17.safetensors",
145
+ "model.layers.13.self_attn.rotary_emb.inv_freq": "model-14-of-17.safetensors",
146
+ "model.layers.14.self_attn.q_proj.weight": "model-15-of-17.safetensors",
147
+ "model.layers.14.self_attn.k_proj.weight": "model-15-of-17.safetensors",
148
+ "model.layers.14.self_attn.v_proj.weight": "model-15-of-17.safetensors",
149
+ "model.layers.14.self_attn.o_proj.weight": "model-15-of-17.safetensors",
150
+ "model.layers.14.input_layernorm.weight": "model-15-of-17.safetensors",
151
+ "model.layers.14.post_attention_layernorm.weight": "model-15-of-17.safetensors",
152
+ "model.layers.14.mlp.gate_proj.weight": "model-15-of-17.safetensors",
153
+ "model.layers.14.mlp.down_proj.weight": "model-15-of-17.safetensors",
154
+ "model.layers.14.mlp.up_proj.weight": "model-15-of-17.safetensors",
155
+ "model.layers.14.self_attn.rotary_emb.inv_freq": "model-15-of-17.safetensors",
156
+ "model.layers.15.self_attn.q_proj.weight": "model-16-of-17.safetensors",
157
+ "model.layers.15.self_attn.k_proj.weight": "model-16-of-17.safetensors",
158
+ "model.layers.15.self_attn.v_proj.weight": "model-16-of-17.safetensors",
159
+ "model.layers.15.self_attn.o_proj.weight": "model-16-of-17.safetensors",
160
+ "model.layers.15.input_layernorm.weight": "model-16-of-17.safetensors",
161
+ "model.layers.15.post_attention_layernorm.weight": "model-16-of-17.safetensors",
162
+ "model.layers.15.mlp.gate_proj.weight": "model-16-of-17.safetensors",
163
+ "model.layers.15.mlp.down_proj.weight": "model-16-of-17.safetensors",
164
+ "model.layers.15.mlp.up_proj.weight": "model-16-of-17.safetensors",
165
+ "model.layers.15.self_attn.rotary_emb.inv_freq": "model-16-of-17.safetensors",
166
+ "model.embed_tokens.weight": "model-17-of-17.safetensors",
167
+ "model.norm.weight": "model-17-of-17.safetensors",
168
+ "lm_head.weight": "model-17-of-17.safetensors"
169
+ }
170
+ }
modeling_moonshot.py ADDED
@@ -0,0 +1,857 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # migrate from https://github.com/huggingface/transformers/blob/e1cec434/src/transformers/models/llama/modeling_llama.py
2
+
3
+ from typing import List, Optional, Tuple, Union
4
+
5
+ import torch
6
+ import torch.nn.functional as F
7
+ import torch.utils.checkpoint
8
+ from torch import nn
9
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
10
+ from einops import rearrange, repeat
11
+
12
+ import transformers
13
+ from packaging import version
14
+ assert version.parse(transformers.__version__) >= version.parse("4.34.1")
15
+
16
+ from transformers.activations import ACT2FN
17
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
18
+ from transformers.modeling_utils import PreTrainedModel
19
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
20
+ from transformers.utils import (
21
+ logging,
22
+ replace_return_docstrings,
23
+ )
24
+ if version.parse(transformers.__version__) >= version.parse("4.35.0"):
25
+ from transformers.utils import is_flash_attn_2_available as is_flash_attn_available
26
+ else:
27
+ from transformers.utils import is_flash_attn_available
28
+ from .configuration_moonshot import MoonshotConfig
29
+ import math
30
+
31
+
32
+ if is_flash_attn_available():
33
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
34
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
35
+ else:
36
+ raise RuntimeError("flash attention must be installed")
37
+
38
+
39
+ logger = logging.get_logger(__name__)
40
+
41
+ _CONFIG_FOR_DOC = "MoonshotConfig"
42
+
43
+
44
+ def _get_unpad_data(padding_mask):
45
+ seqlens_in_batch = padding_mask.sum(dim=-1, dtype=torch.int32)
46
+ indices = torch.nonzero(padding_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.torch.int32), (1, 0))
49
+ return (
50
+ indices,
51
+ cu_seqlens,
52
+ max_seqlen_in_batch,
53
+ )
54
+
55
+ def _upad_input(query_layer, key_layer, value_layer, padding_mask, query_length):
56
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(padding_mask)
57
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
58
+ num_heads = query_layer.shape[2]
59
+
60
+ key_layer = index_first_axis(
61
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
62
+ )
63
+ value_layer = index_first_axis(
64
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
65
+ )
66
+ if query_length == kv_seq_len:
67
+ query_layer = index_first_axis(
68
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
69
+ )
70
+ cu_seqlens_q = cu_seqlens_k
71
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
72
+ indices_q = indices_k
73
+ elif query_length == 1:
74
+ max_seqlen_in_batch_q = 1
75
+ cu_seqlens_q = torch.arange(
76
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
77
+ ) # There is a memcpy here, that is very bad.
78
+ indices_q = cu_seqlens_q[:-1]
79
+ query_layer = query_layer.squeeze(1)
80
+ else:
81
+ # The -q_len: slice assumes left padding.
82
+ padding_mask = padding_mask[:, -query_length:]
83
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, padding_mask)
84
+
85
+ return (
86
+ query_layer,
87
+ key_layer,
88
+ value_layer,
89
+ indices_q,
90
+ (cu_seqlens_q, cu_seqlens_k),
91
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
92
+ )
93
+
94
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
95
+ def _make_causal_mask(
96
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
97
+ ):
98
+ """
99
+ Make causal mask used for bi-directional self-attention.
100
+ """
101
+ bsz, tgt_len = input_ids_shape
102
+ mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
103
+ mask_cond = torch.arange(mask.size(-1), device=device)
104
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
105
+ mask = mask.to(dtype)
106
+
107
+ if past_key_values_length > 0:
108
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
109
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
110
+
111
+
112
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
113
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
114
+ """
115
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
116
+ """
117
+ bsz, src_len = mask.size()
118
+ tgt_len = tgt_len if tgt_len is not None else src_len
119
+
120
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
121
+
122
+ inverted_mask = 1.0 - expanded_mask
123
+
124
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
125
+
126
+
127
+ class RMSNorm(nn.Module):
128
+ def __init__(self, hidden_size, eps=1e-6):
129
+ """
130
+ T5LayerNorm
131
+ """
132
+ super().__init__()
133
+ self.weight = nn.Parameter(torch.ones(hidden_size))
134
+ self.variance_epsilon = eps
135
+
136
+ def forward(self, hidden_states):
137
+ input_dtype = hidden_states.dtype
138
+ hidden_states = hidden_states.to(torch.float32)
139
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
140
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
141
+ return self.weight * hidden_states.to(input_dtype)
142
+
143
+
144
+ ALL_LAYERNORM_LAYERS.append(RMSNorm)
145
+
146
+
147
+ class RotaryEmbedding(nn.Module):
148
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
149
+ super().__init__()
150
+
151
+ self.dim = dim
152
+ self.max_position_embeddings = max_position_embeddings
153
+ self.base = base
154
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
155
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
156
+
157
+ # Build here to make `torch.jit.trace` work.
158
+ self._set_cos_sin_cache(
159
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
160
+ )
161
+
162
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
163
+ self.max_seq_len_cached = seq_len
164
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
165
+
166
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
167
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
168
+ emb = torch.cat((freqs, freqs), dim=-1)
169
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
170
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
171
+
172
+ def forward(self, x, seq_len=None):
173
+ # x: [bs, num_attention_heads, seq_len, head_size]
174
+ if seq_len > self.max_seq_len_cached:
175
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
176
+
177
+ return (
178
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
179
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
180
+ )
181
+
182
+
183
+ class LinearScalingRotaryEmbedding(RotaryEmbedding):
184
+ """RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
185
+
186
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
187
+ self.scaling_factor = scaling_factor
188
+ super().__init__(dim, max_position_embeddings, base, device)
189
+
190
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
191
+ self.max_seq_len_cached = seq_len
192
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
193
+ t = t / self.scaling_factor
194
+
195
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
196
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
197
+ emb = torch.cat((freqs, freqs), dim=-1)
198
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
199
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
200
+
201
+
202
+ def rotate_half(x):
203
+ """Rotates half the hidden dims of the input."""
204
+ x1 = x[..., : x.shape[-1] // 2]
205
+ x2 = x[..., x.shape[-1] // 2 :]
206
+ return torch.cat((-x2, x1), dim=-1)
207
+
208
+
209
+ # Copied from transformers.models.gpt_neox.modeling_gpt_neox.apply_rotary_pos_emb
210
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
211
+ cos = cos[position_ids].unsqueeze(1) # [seq_len, dim] -> [batch_size, 1, seq_len, head_dim]
212
+ sin = sin[position_ids].unsqueeze(1)
213
+ q_embed = (q * cos) + (rotate_half(q) * sin)
214
+ k_embed = (k * cos) + (rotate_half(k) * sin)
215
+ return q_embed, k_embed
216
+
217
+
218
+ class MLP(nn.Module):
219
+ def __init__(self, config):
220
+ super().__init__()
221
+ self.config = config
222
+ self.hidden_size = config.hidden_size
223
+ self.intermediate_size = config.intermediate_size
224
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
225
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
226
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
227
+ self.act_fn = ACT2FN[config.hidden_act]
228
+
229
+ def forward(self, x):
230
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
231
+ return down_proj
232
+
233
+
234
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
235
+ """
236
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
237
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
238
+ """
239
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
240
+ if n_rep == 1:
241
+ return hidden_states
242
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
243
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
244
+
245
+
246
+ class Attention(nn.Module):
247
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
248
+
249
+ def __init__(self, config: MoonshotConfig):
250
+ super().__init__()
251
+ self.config = config
252
+ self.hidden_size = config.hidden_size
253
+ self.num_heads = config.num_attention_heads
254
+ self.head_dim = self.hidden_size // self.num_heads
255
+ self.num_key_value_heads = config.num_key_value_heads
256
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
257
+ self.max_position_embeddings = config.pretraining_sequence_length
258
+ self.rope_theta = config.rope_theta
259
+
260
+ if (self.head_dim * self.num_heads) != self.hidden_size:
261
+ raise ValueError(
262
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
263
+ f" and `num_heads`: {self.num_heads})."
264
+ )
265
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
266
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
267
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
268
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
269
+
270
+ self._init_rope()
271
+
272
+ def _init_rope(self):
273
+
274
+ scaling_type = self.config.rope_scaling["type"]
275
+ scaling_factor = self.config.rope_scaling["factor"]
276
+ if scaling_type == "linear":
277
+ self.rotary_emb = LinearScalingRotaryEmbedding(
278
+ self.head_dim,
279
+ max_position_embeddings=self.max_position_embeddings,
280
+ scaling_factor=scaling_factor,
281
+ base=self.rope_theta,
282
+ )
283
+ else:
284
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
285
+
286
+ def forward(
287
+ self,
288
+ hidden_states: torch.Tensor,
289
+ attention_mask: Optional[torch.Tensor] = None,
290
+ position_ids: Optional[torch.LongTensor] = None,
291
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
292
+ output_attentions: bool = False,
293
+ use_cache: bool = False,
294
+ padding_mask: Optional[torch.LongTensor] = None,
295
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
296
+ # LlamaFlashAttention2 attention does not support output_attentions
297
+ do_prefill = past_key_value is None
298
+
299
+ output_attentions = False
300
+
301
+ bsz, q_len, _ = hidden_states.size()
302
+
303
+ query_states = self.q_proj(hidden_states)
304
+ key_states = self.k_proj(hidden_states)
305
+ value_states = self.v_proj(hidden_states)
306
+
307
+ # Flash attention requires the input to have the shape
308
+ # batch_size x seq_length x head_dime x hidden_dim
309
+ # therefore we just need to keep the original shape
310
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
311
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
312
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
313
+
314
+ kv_seq_len = key_states.shape[-2]
315
+ if past_key_value is not None:
316
+ kv_seq_len += past_key_value[0].shape[-2]
317
+
318
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
319
+
320
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
321
+
322
+ if past_key_value is not None:
323
+ # reuse k, v, self_attention
324
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
325
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
326
+
327
+ past_key_value = (key_states, value_states) if use_cache else None
328
+
329
+ query_states = query_states.transpose(1, 2)
330
+ key_states = key_states.transpose(1, 2)
331
+ value_states = value_states.transpose(1, 2)
332
+
333
+ dropout_rate = 0.0 # if not self.training else self.attn_dropout
334
+
335
+ input_dtype = query_states.dtype
336
+ if input_dtype == torch.float32:
337
+ logger.warning_once(
338
+ "The input hidden states seems to be silently casted in float32, this might be related to"
339
+ " the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
340
+ " float16."
341
+ )
342
+
343
+ query_states = query_states.to(torch.float16)
344
+ key_states = key_states.to(torch.float16)
345
+ value_states = value_states.to(torch.float16)
346
+
347
+ attn_output = self._flash_attention_forward(
348
+ query_states, key_states, value_states, padding_mask, q_len, dropout=dropout_rate
349
+ )
350
+
351
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
352
+ attn_output = self.o_proj(attn_output)
353
+
354
+ if not output_attentions:
355
+ attn_weights = None
356
+
357
+ return attn_output, attn_weights, past_key_value
358
+
359
+
360
+
361
+ def _flash_attention_forward(
362
+ self, query_states, key_states, value_states, padding_mask, query_length, dropout=0.0, softmax_scale=None
363
+ ):
364
+ """
365
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
366
+ first unpad the input, then computes the attention scores and pad the final attention scores.
367
+
368
+ Args:
369
+ query_states (`torch.Tensor`):
370
+ Input query states to be passed to Flash Attention API
371
+ key_states (`torch.Tensor`):
372
+ Input key states to be passed to Flash Attention API
373
+ value_states (`torch.Tensor`):
374
+ Input value states to be passed to Flash Attention API
375
+ padding_mask (`torch.Tensor`):
376
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
377
+ position of padding tokens and 1 for the position of non-padding tokens.
378
+ dropout (`int`, *optional*):
379
+ Attention dropout
380
+ softmax_scale (`float`, *optional*):
381
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
382
+ """
383
+ # Contains at least one padding token in the sequence
384
+ if padding_mask is not None:
385
+ batch_size = query_states.shape[0]
386
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = _upad_input(
387
+ query_states, key_states, value_states, padding_mask, query_length
388
+ )
389
+
390
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
391
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
392
+
393
+ attn_output_unpad = flash_attn_varlen_func(
394
+ query_states,
395
+ key_states,
396
+ value_states,
397
+ cu_seqlens_q=cu_seqlens_q,
398
+ cu_seqlens_k=cu_seqlens_k,
399
+ max_seqlen_q=max_seqlen_in_batch_q,
400
+ max_seqlen_k=max_seqlen_in_batch_k,
401
+ dropout_p=dropout,
402
+ softmax_scale=softmax_scale,
403
+ causal=True,
404
+ )
405
+
406
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
407
+ else:
408
+ attn_output = flash_attn_func(
409
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=True
410
+ )
411
+
412
+ return attn_output
413
+
414
+
415
+ class DecoderLayer(nn.Module):
416
+ def __init__(self, config: MoonshotConfig):
417
+ super().__init__()
418
+ self.hidden_size = config.hidden_size
419
+ self.config = config
420
+ self.self_attn = Attention(config=config)
421
+ self.mlp = MLP(config)
422
+ self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
423
+ self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
424
+
425
+ def forward(
426
+ self,
427
+ hidden_states: torch.Tensor,
428
+ attention_mask: Optional[torch.Tensor] = None,
429
+ position_ids: Optional[torch.LongTensor] = None,
430
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
431
+ output_attentions: Optional[bool] = False,
432
+ use_cache: Optional[bool] = False,
433
+ padding_mask: Optional[torch.LongTensor] = None,
434
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
435
+ """
436
+ Args:
437
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
438
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
439
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
440
+ output_attentions (`bool`, *optional*):
441
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
442
+ returned tensors for more detail.
443
+ use_cache (`bool`, *optional*):
444
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
445
+ (see `past_key_values`).
446
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
447
+ """
448
+
449
+ residual = hidden_states
450
+
451
+ hidden_states = self.input_layernorm(hidden_states)
452
+
453
+ # Self Attention
454
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
455
+ hidden_states=hidden_states,
456
+ attention_mask=attention_mask,
457
+ position_ids=position_ids,
458
+ past_key_value=past_key_value,
459
+ output_attentions=output_attentions,
460
+ use_cache=use_cache,
461
+ padding_mask=padding_mask,
462
+ )
463
+ hidden_states = residual + hidden_states
464
+
465
+ # Fully Connected
466
+ residual = hidden_states
467
+ hidden_states = self.post_attention_layernorm(hidden_states)
468
+ hidden_states = self.mlp(hidden_states)
469
+ hidden_states = residual + hidden_states
470
+
471
+ outputs = (hidden_states,)
472
+
473
+ if output_attentions:
474
+ outputs += (self_attn_weights,)
475
+
476
+ if use_cache:
477
+ outputs += (present_key_value,)
478
+
479
+ return outputs
480
+
481
+
482
+ class MoonshotPreTrainedModel(PreTrainedModel):
483
+ config_class = MoonshotConfig
484
+ base_model_prefix = "model"
485
+ supports_gradient_checkpointing = True
486
+ _no_split_modules = ["DecoderLayer"]
487
+ _skip_keys_device_placement = "past_key_values"
488
+ _supports_flash_attn_2 = True
489
+
490
+ def _init_weights(self, module):
491
+ std = self.config.initializer_range
492
+ if isinstance(module, nn.Linear):
493
+ module.weight.data.normal_(mean=0.0, std=std)
494
+ if module.bias is not None:
495
+ module.bias.data.zero_()
496
+ elif isinstance(module, nn.Embedding):
497
+ module.weight.data.normal_(mean=0.0, std=std)
498
+ if module.padding_idx is not None:
499
+ module.weight.data[module.padding_idx].zero_()
500
+
501
+ def _set_gradient_checkpointing(self, module, value=False):
502
+ if isinstance(module, MoonshotModel):
503
+ module.gradient_checkpointing = value
504
+
505
+
506
+ class MoonshotModel(MoonshotPreTrainedModel):
507
+ """
508
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DecoderLayer`]
509
+
510
+ Args:
511
+ config: MoonshotConfig
512
+ """
513
+
514
+ def __init__(self, config: MoonshotConfig):
515
+ super().__init__(config)
516
+ self.padding_idx = config.pad_token_id
517
+ self.vocab_size = config.vocab_size
518
+
519
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
520
+ self.layers = nn.ModuleList([DecoderLayer(config) for _ in range(config.num_hidden_layers)])
521
+ self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
522
+
523
+ self.gradient_checkpointing = False
524
+ # Initialize weights and apply final processing
525
+ self.post_init()
526
+
527
+ def get_input_embeddings(self):
528
+ return self.embed_tokens
529
+
530
+ def set_input_embeddings(self, value):
531
+ self.embed_tokens = value
532
+
533
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
534
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
535
+ # create causal mask
536
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
537
+ combined_attention_mask = None
538
+ if input_shape[-1] > 1:
539
+ combined_attention_mask = _make_causal_mask(
540
+ input_shape,
541
+ inputs_embeds.dtype,
542
+ device=inputs_embeds.device,
543
+ past_key_values_length=past_key_values_length,
544
+ )
545
+
546
+ if attention_mask is not None:
547
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
548
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
549
+ inputs_embeds.device
550
+ )
551
+ combined_attention_mask = (
552
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
553
+ )
554
+
555
+ return combined_attention_mask
556
+
557
+ def forward(
558
+ self,
559
+ input_ids: torch.LongTensor = None,
560
+ attention_mask: Optional[torch.Tensor] = None,
561
+ position_ids: Optional[torch.LongTensor] = None,
562
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
563
+ inputs_embeds: Optional[torch.FloatTensor] = None,
564
+ use_cache: Optional[bool] = None,
565
+ output_attentions: Optional[bool] = None,
566
+ output_hidden_states: Optional[bool] = None,
567
+ return_dict: Optional[bool] = None,
568
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
569
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
570
+ output_hidden_states = (
571
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
572
+ )
573
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
574
+
575
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
576
+
577
+ # retrieve input_ids and inputs_embeds
578
+ if input_ids is not None and inputs_embeds is not None:
579
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
580
+ elif input_ids is not None:
581
+ batch_size, seq_length = input_ids.shape
582
+ elif inputs_embeds is not None:
583
+ batch_size, seq_length, _ = inputs_embeds.shape
584
+ else:
585
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
586
+
587
+ seq_length_with_past = seq_length
588
+ past_key_values_length = 0
589
+
590
+ if past_key_values is not None:
591
+ past_key_values_length = past_key_values[0][0].shape[2]
592
+ seq_length_with_past = seq_length_with_past + past_key_values_length
593
+
594
+ if position_ids is None:
595
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
596
+ position_ids = torch.arange(
597
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
598
+ )
599
+ position_ids = position_ids.unsqueeze(0)
600
+
601
+ if inputs_embeds is None:
602
+ inputs_embeds = self.embed_tokens(input_ids)
603
+ # embed positions
604
+ # TODO kill attention_mask for prefill
605
+ if self.training:
606
+ if attention_mask is None:
607
+ attention_mask = torch.ones(
608
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
609
+ )
610
+ padding_mask = None
611
+ else:
612
+ if 0 in attention_mask:
613
+ padding_mask = attention_mask
614
+ else:
615
+ padding_mask = None
616
+
617
+ attention_mask = self._prepare_decoder_attention_mask(
618
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
619
+ )
620
+ else:
621
+ padding_mask = attention_mask
622
+
623
+ hidden_states = inputs_embeds
624
+
625
+ if self.gradient_checkpointing and self.training:
626
+ if use_cache:
627
+ logger.warning_once(
628
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
629
+ )
630
+ use_cache = False
631
+
632
+ # decoder layers
633
+ all_hidden_states = () if output_hidden_states else None
634
+ all_self_attns = () if output_attentions else None
635
+ next_decoder_cache = () if use_cache else None
636
+
637
+ for idx, decoder_layer in enumerate(self.layers):
638
+ if output_hidden_states:
639
+ all_hidden_states += (hidden_states,)
640
+
641
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
642
+
643
+ if self.gradient_checkpointing and self.training:
644
+
645
+ def create_custom_forward(module):
646
+ def custom_forward(*inputs):
647
+ # None for past_key_value
648
+ return module(*inputs, past_key_value, output_attentions, padding_mask=padding_mask)
649
+
650
+ return custom_forward
651
+
652
+ layer_outputs = torch.utils.checkpoint.checkpoint(
653
+ create_custom_forward(decoder_layer), hidden_states, attention_mask, position_ids
654
+ )
655
+ else:
656
+ layer_outputs = decoder_layer(
657
+ hidden_states,
658
+ attention_mask=attention_mask,
659
+ position_ids=position_ids,
660
+ past_key_value=past_key_value,
661
+ output_attentions=output_attentions,
662
+ use_cache=use_cache,
663
+ padding_mask=padding_mask,
664
+ )
665
+
666
+ hidden_states = layer_outputs[0]
667
+
668
+ if use_cache:
669
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
670
+
671
+ if output_attentions:
672
+ all_self_attns += (layer_outputs[1],)
673
+
674
+ hidden_states = self.norm(hidden_states)
675
+
676
+ # add hidden states from the last decoder layer
677
+ if output_hidden_states:
678
+ all_hidden_states += (hidden_states,)
679
+
680
+ next_cache = next_decoder_cache if use_cache else None
681
+ if not return_dict:
682
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
683
+ return BaseModelOutputWithPast(
684
+ last_hidden_state=hidden_states,
685
+ past_key_values=next_cache,
686
+ hidden_states=all_hidden_states,
687
+ attentions=all_self_attns,
688
+ )
689
+
690
+
691
+ class MoonshotForCausalLM(MoonshotPreTrainedModel):
692
+ _tied_weights_keys = ["lm_head.weight"]
693
+
694
+ def __init__(self, config):
695
+ super().__init__(config)
696
+ self.model = MoonshotModel(config)
697
+ self.vocab_size = config.vocab_size
698
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
699
+
700
+ # Initialize weights and apply final processing
701
+ self.post_init()
702
+
703
+ def get_input_embeddings(self):
704
+ return self.model.embed_tokens
705
+
706
+ def set_input_embeddings(self, value):
707
+ self.model.embed_tokens = value
708
+
709
+ def get_output_embeddings(self):
710
+ return self.lm_head
711
+
712
+ def set_output_embeddings(self, new_embeddings):
713
+ self.lm_head = new_embeddings
714
+
715
+ def set_decoder(self, decoder):
716
+ self.model = decoder
717
+
718
+ def get_decoder(self):
719
+ return self.model
720
+
721
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
722
+ def forward(
723
+ self,
724
+ input_ids: torch.LongTensor = None,
725
+ attention_mask: Optional[torch.Tensor] = None,
726
+ position_ids: Optional[torch.LongTensor] = None,
727
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
728
+ inputs_embeds: Optional[torch.FloatTensor] = None,
729
+ labels: Optional[torch.LongTensor] = None,
730
+ use_cache: Optional[bool] = None,
731
+ output_attentions: Optional[bool] = None,
732
+ output_hidden_states: Optional[bool] = None,
733
+ generation_mode: Optional[bool] = None,
734
+ return_dict: Optional[bool] = None,
735
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
736
+ r"""
737
+ Args:
738
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
739
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
740
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
741
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
742
+
743
+ Returns:
744
+
745
+ Example:
746
+
747
+ ```python
748
+ >>> from transformers import AutoTokenizer, MoonshotForCausalLM
749
+
750
+ >>> model = MoonshotForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
751
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
752
+
753
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
754
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
755
+
756
+ >>> # Generate
757
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
758
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
759
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
760
+ ```"""
761
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
762
+ output_hidden_states = (
763
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
764
+ )
765
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
766
+
767
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
768
+ outputs = self.model(
769
+ input_ids=input_ids,
770
+ attention_mask=attention_mask,
771
+ position_ids=position_ids,
772
+ past_key_values=past_key_values,
773
+ inputs_embeds=inputs_embeds,
774
+ use_cache=use_cache,
775
+ output_attentions=output_attentions,
776
+ output_hidden_states=output_hidden_states,
777
+ return_dict=return_dict,
778
+ )
779
+
780
+ logits = outputs[0]
781
+ if generation_mode:
782
+ logits = logits[:, -1:]
783
+ logits = self.lm_head(logits)
784
+ # logits = logits.float()
785
+
786
+ loss = None
787
+ if labels is not None:
788
+ # Shift so that tokens < n predict n
789
+ shift_logits = logits[..., :-1, :].contiguous()
790
+ shift_labels = labels[..., 1:].contiguous()
791
+ # Flatten the tokens
792
+ loss_fct = CrossEntropyLoss()
793
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
794
+ shift_labels = shift_labels.view(-1)
795
+ # Enable model parallelism
796
+ shift_labels = shift_labels.to(shift_logits.device)
797
+ loss = loss_fct(shift_logits, shift_labels)
798
+
799
+ if not return_dict:
800
+ output = (logits,) + outputs[1:]
801
+ return (loss,) + output if loss is not None else output
802
+
803
+ return CausalLMOutputWithPast(
804
+ loss=loss,
805
+ logits=logits,
806
+ past_key_values=outputs.past_key_values,
807
+ hidden_states=outputs.hidden_states,
808
+ attentions=outputs.attentions,
809
+ )
810
+
811
+ def prepare_inputs_for_generation(
812
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
813
+ ):
814
+ if past_key_values is not None:
815
+ past_length = past_key_values[0][0].shape[2]
816
+
817
+ # Some generation methods already pass only the last input ID
818
+ if input_ids.shape[1] > past_length:
819
+ remove_prefix_length = past_length
820
+ else:
821
+ # Default to old behavior: keep only final ID
822
+ remove_prefix_length = input_ids.shape[1] - 1
823
+
824
+ input_ids = input_ids[:, remove_prefix_length:]
825
+
826
+ position_ids = kwargs.get("position_ids", None)
827
+ if attention_mask is not None and position_ids is None:
828
+ # create position_ids on the fly for batch generation
829
+ position_ids = attention_mask.long().cumsum(-1) - 1
830
+ position_ids.masked_fill_(attention_mask == 0, 1)
831
+ if past_key_values:
832
+ position_ids = position_ids[:, -input_ids.shape[1] :]
833
+
834
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
835
+ if inputs_embeds is not None and past_key_values is None:
836
+ model_inputs = {"inputs_embeds": inputs_embeds}
837
+ else:
838
+ model_inputs = {"input_ids": input_ids}
839
+
840
+ model_inputs.update(
841
+ {
842
+ "position_ids": position_ids,
843
+ "past_key_values": past_key_values,
844
+ "use_cache": kwargs.get("use_cache"),
845
+ "attention_mask": attention_mask,
846
+ }
847
+ )
848
+ return model_inputs
849
+
850
+ @staticmethod
851
+ def _reorder_cache(past_key_values, beam_idx):
852
+ reordered_past = ()
853
+ for layer_past in past_key_values:
854
+ reordered_past += (
855
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
856
+ )
857
+ return reordered_past