mrfakename commited on
Commit
137714a
·
verified ·
1 Parent(s): 41f3c12

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