namespace-Pt commited on
Commit
442ebf0
·
verified ·
1 Parent(s): edd69d1

Upload folder using huggingface_hub

Browse files
added_tokens.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "<|endoftext|>": 151643,
3
+ "<|im_end|>": 151645,
4
+ "<|im_start|>": 151644
5
+ }
config.json ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "beacon-qwen-2-7b-instruct",
3
+ "architectures": [
4
+ "Qwen2ForCausalLM"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_qwen2.Qwen2Config",
8
+ "AutoModelForCausalLM": "modeling_qwen2.Qwen2ForCausalLM"
9
+ },
10
+ "attention_dropout": 0.0,
11
+ "beacon_attend_prev": true,
12
+ "beacon_attn": "full-coverage",
13
+ "beacon_embed_init": "eos",
14
+ "beacon_parallel_window": 1,
15
+ "beacon_param": [
16
+ "q",
17
+ "k",
18
+ "v"
19
+ ],
20
+ "beacon_pos": "interleave",
21
+ "beacon_ratio": [
22
+ 2,
23
+ 4,
24
+ 8,
25
+ 16,
26
+ 32
27
+ ],
28
+ "beacon_ratio_mix": "step-random",
29
+ "beacon_sink_size": 0,
30
+ "beacon_stride": 2048,
31
+ "beacon_window": 2048,
32
+ "bos_token_id": 151643,
33
+ "eos_token_id": 151645,
34
+ "hidden_act": "silu",
35
+ "hidden_size": 3584,
36
+ "initializer_range": 0.02,
37
+ "intermediate_size": 18944,
38
+ "max_position_embeddings": 32768,
39
+ "max_window_layers": 28,
40
+ "model_type": "qwen2",
41
+ "num_attention_heads": 28,
42
+ "num_hidden_layers": 28,
43
+ "num_key_value_heads": 4,
44
+ "rms_norm_eps": 1e-06,
45
+ "rope_scaling": null,
46
+ "rope_theta": 1000000.0,
47
+ "sliding_window": 131072,
48
+ "tie_word_embeddings": false,
49
+ "torch_dtype": "bfloat16",
50
+ "transformers_version": "4.39.3",
51
+ "use_cache": true,
52
+ "use_sliding_window": false,
53
+ "vocab_size": 152064
54
+ }
configuration_qwen2.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ Qwen2 model configuration"""
16
+
17
+ from transformers.configuration_utils import PretrainedConfig
18
+ from transformers.utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+ QWEN2_PRETRAINED_CONFIG_ARCHIVE_MAP = {
24
+ "Qwen/Qwen2-7B-beta": "https://huggingface.co/Qwen/Qwen2-7B-beta/resolve/main/config.json",
25
+ }
26
+
27
+
28
+ class Qwen2Config(PretrainedConfig):
29
+ r"""
30
+ This is the configuration class to store the configuration of a [`Qwen2Model`]. It is used to instantiate a
31
+ Qwen2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
32
+ with the defaults will yield a similar configuration to that of
33
+ Qwen2-7B-beta [Qwen/Qwen2-7B-beta](https://huggingface.co/Qwen/Qwen2-7B-beta).
34
+
35
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
36
+ documentation from [`PretrainedConfig`] for more information.
37
+
38
+
39
+ Args:
40
+ vocab_size (`int`, *optional*, defaults to 151936):
41
+ Vocabulary size of the Qwen2 model. Defines the number of different tokens that can be represented by the
42
+ `inputs_ids` passed when calling [`Qwen2Model`]
43
+ hidden_size (`int`, *optional*, defaults to 4096):
44
+ Dimension of the hidden representations.
45
+ intermediate_size (`int`, *optional*, defaults to 22016):
46
+ Dimension of the MLP representations.
47
+ num_hidden_layers (`int`, *optional*, defaults to 32):
48
+ Number of hidden layers in the Transformer encoder.
49
+ num_attention_heads (`int`, *optional*, defaults to 32):
50
+ Number of attention heads for each attention layer in the Transformer encoder.
51
+ num_key_value_heads (`int`, *optional*, defaults to 32):
52
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
53
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
54
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
55
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
56
+ by meanpooling all the original heads within that group. For more details checkout [this
57
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
58
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
59
+ The non-linear activation function (function or string) in the decoder.
60
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
61
+ The maximum sequence length that this model might ever be used with.
62
+ initializer_range (`float`, *optional*, defaults to 0.02):
63
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
64
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
65
+ The epsilon used by the rms normalization layers.
66
+ use_cache (`bool`, *optional*, defaults to `True`):
67
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
68
+ relevant if `config.is_decoder=True`.
69
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
70
+ Whether the model's input and output word embeddings should be tied.
71
+ rope_theta (`float`, *optional*, defaults to 10000.0):
72
+ The base period of the RoPE embeddings.
73
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
74
+ Whether to use sliding window attention.
75
+ sliding_window (`int`, *optional*, defaults to 4096):
76
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
77
+ max_window_layers (`int`, *optional*, defaults to 28):
78
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
79
+ attention_dropout (`float`, *optional*, defaults to 0.0):
80
+ The dropout ratio for the attention probabilities.
81
+
82
+ ```python
83
+ >>> from transformers import Qwen2Model, Qwen2Config
84
+
85
+ >>> # Initializing a Qwen2 style configuration
86
+ >>> configuration = Qwen2Config()
87
+
88
+ >>> # Initializing a model from the Qwen2-7B style configuration
89
+ >>> model = Qwen2Model(configuration)
90
+
91
+ >>> # Accessing the model configuration
92
+ >>> configuration = model.config
93
+ ```"""
94
+
95
+ model_type = "qwen2"
96
+ keys_to_ignore_at_inference = ["past_key_values"]
97
+
98
+ def __init__(
99
+ self,
100
+ vocab_size=151936,
101
+ hidden_size=4096,
102
+ intermediate_size=22016,
103
+ num_hidden_layers=32,
104
+ num_attention_heads=32,
105
+ num_key_value_heads=32,
106
+ hidden_act="silu",
107
+ max_position_embeddings=32768,
108
+ initializer_range=0.02,
109
+ rms_norm_eps=1e-6,
110
+ use_cache=True,
111
+ tie_word_embeddings=False,
112
+ rope_theta=10000.0,
113
+ use_sliding_window=False,
114
+ sliding_window=4096,
115
+ rope_scaling=None,
116
+ max_window_layers=28,
117
+ attention_dropout=0.0,
118
+ beacon_window=2048,
119
+ beacon_stride=2048,
120
+ beacon_attn="full-coverage",
121
+ beacon_ratio=[2,4,8,16,32],
122
+ beacon_ratio_mix="step-random",
123
+ beacon_param=[],
124
+ beacon_embed_init="eos",
125
+ beacon_sink_size=0,
126
+ beacon_attend_prev=True,
127
+ beacon_pos="interleave",
128
+ beacon_parallel_window=1,
129
+ **kwargs,
130
+ ):
131
+ self.vocab_size = vocab_size
132
+ self.max_position_embeddings = max_position_embeddings
133
+ self.hidden_size = hidden_size
134
+ self.intermediate_size = intermediate_size
135
+ self.num_hidden_layers = num_hidden_layers
136
+ self.num_attention_heads = num_attention_heads
137
+ self.use_sliding_window = use_sliding_window
138
+ self.sliding_window = sliding_window
139
+ self.max_window_layers = max_window_layers
140
+ self.rope_scaling = rope_scaling
141
+
142
+ # for backward compatibility
143
+ if num_key_value_heads is None:
144
+ num_key_value_heads = num_attention_heads
145
+
146
+ self.num_key_value_heads = num_key_value_heads
147
+ self.hidden_act = hidden_act
148
+ self.initializer_range = initializer_range
149
+ self.rms_norm_eps = rms_norm_eps
150
+ self.use_cache = use_cache
151
+ self.rope_theta = rope_theta
152
+ self.attention_dropout = attention_dropout
153
+
154
+ self.beacon_window = beacon_window
155
+ self.beacon_stride = beacon_stride
156
+ self.beacon_attn = beacon_attn
157
+ self.beacon_ratio = beacon_ratio
158
+ self.beacon_ratio_mix = beacon_ratio_mix
159
+ self.beacon_param = beacon_param
160
+ self.beacon_embed_init = beacon_embed_init
161
+ self.beacon_sink_size = beacon_sink_size
162
+ self.beacon_attend_prev = beacon_attend_prev
163
+ self.beacon_pos = beacon_pos
164
+ self.beacon_parallel_window = beacon_parallel_window
165
+
166
+ super().__init__(
167
+ tie_word_embeddings=tie_word_embeddings,
168
+ **kwargs,
169
+ )
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 151643,
4
+ "eos_token_id": 151645,
5
+ "transformers_version": "4.39.3"
6
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model-00001-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:49bd2bf5cb28ba373973c3333bbb1141392dfbe738f0641636e542702805fa86
3
+ size 4947453128
model-00002-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2cccd28f08ed827dfe0e3d2fea66e666c76149aa9fc8d5f53278dc1000706144
3
+ size 4991570400
model-00003-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c1ae6de370ab35ded7b2d77ad562fd908bac8620108dd4fcd0045c198375e6e6
3
+ size 4991570464
model-00004-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:be55956e1438674b224d89ead13eb3f344889917899b7b5f5d321520255e7159
3
+ size 1225807416
model.safetensors.index.json ADDED
@@ -0,0 +1,515 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 16156342272
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-00004-of-00004.safetensors",
7
+ "model.beacon_embed_tokens.weight": "model-00001-of-00004.safetensors",
8
+ "model.embed_tokens.weight": "model-00001-of-00004.safetensors",
9
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00004.safetensors",
10
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
11
+ "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
12
+ "model.layers.0.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
13
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
14
+ "model.layers.0.self_attn.beacon_k_proj.bias": "model-00001-of-00004.safetensors",
15
+ "model.layers.0.self_attn.beacon_k_proj.weight": "model-00001-of-00004.safetensors",
16
+ "model.layers.0.self_attn.beacon_q_proj.bias": "model-00001-of-00004.safetensors",
17
+ "model.layers.0.self_attn.beacon_q_proj.weight": "model-00001-of-00004.safetensors",
18
+ "model.layers.0.self_attn.beacon_v_proj.bias": "model-00001-of-00004.safetensors",
19
+ "model.layers.0.self_attn.beacon_v_proj.weight": "model-00001-of-00004.safetensors",
20
+ "model.layers.0.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
21
+ "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
22
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
23
+ "model.layers.0.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
24
+ "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
25
+ "model.layers.0.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
26
+ "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
27
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00004.safetensors",
28
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
29
+ "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
30
+ "model.layers.1.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
31
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
32
+ "model.layers.1.self_attn.beacon_k_proj.bias": "model-00001-of-00004.safetensors",
33
+ "model.layers.1.self_attn.beacon_k_proj.weight": "model-00001-of-00004.safetensors",
34
+ "model.layers.1.self_attn.beacon_q_proj.bias": "model-00001-of-00004.safetensors",
35
+ "model.layers.1.self_attn.beacon_q_proj.weight": "model-00001-of-00004.safetensors",
36
+ "model.layers.1.self_attn.beacon_v_proj.bias": "model-00001-of-00004.safetensors",
37
+ "model.layers.1.self_attn.beacon_v_proj.weight": "model-00001-of-00004.safetensors",
38
+ "model.layers.1.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
39
+ "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
40
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
41
+ "model.layers.1.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
42
+ "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
43
+ "model.layers.1.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
44
+ "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
45
+ "model.layers.10.input_layernorm.weight": "model-00002-of-00004.safetensors",
46
+ "model.layers.10.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
47
+ "model.layers.10.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
48
+ "model.layers.10.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
49
+ "model.layers.10.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
50
+ "model.layers.10.self_attn.beacon_k_proj.bias": "model-00002-of-00004.safetensors",
51
+ "model.layers.10.self_attn.beacon_k_proj.weight": "model-00002-of-00004.safetensors",
52
+ "model.layers.10.self_attn.beacon_q_proj.bias": "model-00002-of-00004.safetensors",
53
+ "model.layers.10.self_attn.beacon_q_proj.weight": "model-00002-of-00004.safetensors",
54
+ "model.layers.10.self_attn.beacon_v_proj.bias": "model-00002-of-00004.safetensors",
55
+ "model.layers.10.self_attn.beacon_v_proj.weight": "model-00002-of-00004.safetensors",
56
+ "model.layers.10.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
57
+ "model.layers.10.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
58
+ "model.layers.10.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
59
+ "model.layers.10.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
60
+ "model.layers.10.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
61
+ "model.layers.10.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
62
+ "model.layers.10.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
63
+ "model.layers.11.input_layernorm.weight": "model-00002-of-00004.safetensors",
64
+ "model.layers.11.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
65
+ "model.layers.11.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
66
+ "model.layers.11.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
67
+ "model.layers.11.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
68
+ "model.layers.11.self_attn.beacon_k_proj.bias": "model-00002-of-00004.safetensors",
69
+ "model.layers.11.self_attn.beacon_k_proj.weight": "model-00002-of-00004.safetensors",
70
+ "model.layers.11.self_attn.beacon_q_proj.bias": "model-00002-of-00004.safetensors",
71
+ "model.layers.11.self_attn.beacon_q_proj.weight": "model-00002-of-00004.safetensors",
72
+ "model.layers.11.self_attn.beacon_v_proj.bias": "model-00002-of-00004.safetensors",
73
+ "model.layers.11.self_attn.beacon_v_proj.weight": "model-00002-of-00004.safetensors",
74
+ "model.layers.11.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
75
+ "model.layers.11.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
76
+ "model.layers.11.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
77
+ "model.layers.11.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
78
+ "model.layers.11.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
79
+ "model.layers.11.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
80
+ "model.layers.11.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
81
+ "model.layers.12.input_layernorm.weight": "model-00002-of-00004.safetensors",
82
+ "model.layers.12.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
83
+ "model.layers.12.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
84
+ "model.layers.12.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
85
+ "model.layers.12.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
86
+ "model.layers.12.self_attn.beacon_k_proj.bias": "model-00002-of-00004.safetensors",
87
+ "model.layers.12.self_attn.beacon_k_proj.weight": "model-00002-of-00004.safetensors",
88
+ "model.layers.12.self_attn.beacon_q_proj.bias": "model-00002-of-00004.safetensors",
89
+ "model.layers.12.self_attn.beacon_q_proj.weight": "model-00002-of-00004.safetensors",
90
+ "model.layers.12.self_attn.beacon_v_proj.bias": "model-00002-of-00004.safetensors",
91
+ "model.layers.12.self_attn.beacon_v_proj.weight": "model-00002-of-00004.safetensors",
92
+ "model.layers.12.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
93
+ "model.layers.12.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
94
+ "model.layers.12.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
95
+ "model.layers.12.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
96
+ "model.layers.12.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
97
+ "model.layers.12.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
98
+ "model.layers.12.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
99
+ "model.layers.13.input_layernorm.weight": "model-00002-of-00004.safetensors",
100
+ "model.layers.13.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
101
+ "model.layers.13.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
102
+ "model.layers.13.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
103
+ "model.layers.13.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
104
+ "model.layers.13.self_attn.beacon_k_proj.bias": "model-00002-of-00004.safetensors",
105
+ "model.layers.13.self_attn.beacon_k_proj.weight": "model-00002-of-00004.safetensors",
106
+ "model.layers.13.self_attn.beacon_q_proj.bias": "model-00002-of-00004.safetensors",
107
+ "model.layers.13.self_attn.beacon_q_proj.weight": "model-00002-of-00004.safetensors",
108
+ "model.layers.13.self_attn.beacon_v_proj.bias": "model-00002-of-00004.safetensors",
109
+ "model.layers.13.self_attn.beacon_v_proj.weight": "model-00002-of-00004.safetensors",
110
+ "model.layers.13.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
111
+ "model.layers.13.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
112
+ "model.layers.13.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
113
+ "model.layers.13.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
114
+ "model.layers.13.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
115
+ "model.layers.13.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
116
+ "model.layers.13.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
117
+ "model.layers.14.input_layernorm.weight": "model-00002-of-00004.safetensors",
118
+ "model.layers.14.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
119
+ "model.layers.14.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
120
+ "model.layers.14.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
121
+ "model.layers.14.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
122
+ "model.layers.14.self_attn.beacon_k_proj.bias": "model-00002-of-00004.safetensors",
123
+ "model.layers.14.self_attn.beacon_k_proj.weight": "model-00002-of-00004.safetensors",
124
+ "model.layers.14.self_attn.beacon_q_proj.bias": "model-00002-of-00004.safetensors",
125
+ "model.layers.14.self_attn.beacon_q_proj.weight": "model-00002-of-00004.safetensors",
126
+ "model.layers.14.self_attn.beacon_v_proj.bias": "model-00002-of-00004.safetensors",
127
+ "model.layers.14.self_attn.beacon_v_proj.weight": "model-00002-of-00004.safetensors",
128
+ "model.layers.14.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
129
+ "model.layers.14.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
130
+ "model.layers.14.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
131
+ "model.layers.14.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
132
+ "model.layers.14.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
133
+ "model.layers.14.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
134
+ "model.layers.14.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
135
+ "model.layers.15.input_layernorm.weight": "model-00002-of-00004.safetensors",
136
+ "model.layers.15.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
137
+ "model.layers.15.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
138
+ "model.layers.15.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
139
+ "model.layers.15.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
140
+ "model.layers.15.self_attn.beacon_k_proj.bias": "model-00002-of-00004.safetensors",
141
+ "model.layers.15.self_attn.beacon_k_proj.weight": "model-00002-of-00004.safetensors",
142
+ "model.layers.15.self_attn.beacon_q_proj.bias": "model-00002-of-00004.safetensors",
143
+ "model.layers.15.self_attn.beacon_q_proj.weight": "model-00002-of-00004.safetensors",
144
+ "model.layers.15.self_attn.beacon_v_proj.bias": "model-00002-of-00004.safetensors",
145
+ "model.layers.15.self_attn.beacon_v_proj.weight": "model-00002-of-00004.safetensors",
146
+ "model.layers.15.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
147
+ "model.layers.15.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
148
+ "model.layers.15.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
149
+ "model.layers.15.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
150
+ "model.layers.15.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
151
+ "model.layers.15.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
152
+ "model.layers.15.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
153
+ "model.layers.16.input_layernorm.weight": "model-00002-of-00004.safetensors",
154
+ "model.layers.16.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
155
+ "model.layers.16.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
156
+ "model.layers.16.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
157
+ "model.layers.16.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
158
+ "model.layers.16.self_attn.beacon_k_proj.bias": "model-00002-of-00004.safetensors",
159
+ "model.layers.16.self_attn.beacon_k_proj.weight": "model-00002-of-00004.safetensors",
160
+ "model.layers.16.self_attn.beacon_q_proj.bias": "model-00002-of-00004.safetensors",
161
+ "model.layers.16.self_attn.beacon_q_proj.weight": "model-00002-of-00004.safetensors",
162
+ "model.layers.16.self_attn.beacon_v_proj.bias": "model-00002-of-00004.safetensors",
163
+ "model.layers.16.self_attn.beacon_v_proj.weight": "model-00002-of-00004.safetensors",
164
+ "model.layers.16.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
165
+ "model.layers.16.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
166
+ "model.layers.16.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
167
+ "model.layers.16.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
168
+ "model.layers.16.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
169
+ "model.layers.16.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
170
+ "model.layers.16.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
171
+ "model.layers.17.input_layernorm.weight": "model-00003-of-00004.safetensors",
172
+ "model.layers.17.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
173
+ "model.layers.17.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
174
+ "model.layers.17.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
175
+ "model.layers.17.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
176
+ "model.layers.17.self_attn.beacon_k_proj.bias": "model-00002-of-00004.safetensors",
177
+ "model.layers.17.self_attn.beacon_k_proj.weight": "model-00002-of-00004.safetensors",
178
+ "model.layers.17.self_attn.beacon_q_proj.bias": "model-00002-of-00004.safetensors",
179
+ "model.layers.17.self_attn.beacon_q_proj.weight": "model-00002-of-00004.safetensors",
180
+ "model.layers.17.self_attn.beacon_v_proj.bias": "model-00002-of-00004.safetensors",
181
+ "model.layers.17.self_attn.beacon_v_proj.weight": "model-00002-of-00004.safetensors",
182
+ "model.layers.17.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
183
+ "model.layers.17.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
184
+ "model.layers.17.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
185
+ "model.layers.17.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
186
+ "model.layers.17.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
187
+ "model.layers.17.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
188
+ "model.layers.17.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
189
+ "model.layers.18.input_layernorm.weight": "model-00003-of-00004.safetensors",
190
+ "model.layers.18.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
191
+ "model.layers.18.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
192
+ "model.layers.18.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
193
+ "model.layers.18.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
194
+ "model.layers.18.self_attn.beacon_k_proj.bias": "model-00003-of-00004.safetensors",
195
+ "model.layers.18.self_attn.beacon_k_proj.weight": "model-00003-of-00004.safetensors",
196
+ "model.layers.18.self_attn.beacon_q_proj.bias": "model-00003-of-00004.safetensors",
197
+ "model.layers.18.self_attn.beacon_q_proj.weight": "model-00003-of-00004.safetensors",
198
+ "model.layers.18.self_attn.beacon_v_proj.bias": "model-00003-of-00004.safetensors",
199
+ "model.layers.18.self_attn.beacon_v_proj.weight": "model-00003-of-00004.safetensors",
200
+ "model.layers.18.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
201
+ "model.layers.18.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
202
+ "model.layers.18.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
203
+ "model.layers.18.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
204
+ "model.layers.18.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
205
+ "model.layers.18.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
206
+ "model.layers.18.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
207
+ "model.layers.19.input_layernorm.weight": "model-00003-of-00004.safetensors",
208
+ "model.layers.19.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
209
+ "model.layers.19.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
210
+ "model.layers.19.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
211
+ "model.layers.19.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
212
+ "model.layers.19.self_attn.beacon_k_proj.bias": "model-00003-of-00004.safetensors",
213
+ "model.layers.19.self_attn.beacon_k_proj.weight": "model-00003-of-00004.safetensors",
214
+ "model.layers.19.self_attn.beacon_q_proj.bias": "model-00003-of-00004.safetensors",
215
+ "model.layers.19.self_attn.beacon_q_proj.weight": "model-00003-of-00004.safetensors",
216
+ "model.layers.19.self_attn.beacon_v_proj.bias": "model-00003-of-00004.safetensors",
217
+ "model.layers.19.self_attn.beacon_v_proj.weight": "model-00003-of-00004.safetensors",
218
+ "model.layers.19.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
219
+ "model.layers.19.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
220
+ "model.layers.19.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
221
+ "model.layers.19.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
222
+ "model.layers.19.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
223
+ "model.layers.19.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
224
+ "model.layers.19.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
225
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00004.safetensors",
226
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
227
+ "model.layers.2.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
228
+ "model.layers.2.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
229
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
230
+ "model.layers.2.self_attn.beacon_k_proj.bias": "model-00001-of-00004.safetensors",
231
+ "model.layers.2.self_attn.beacon_k_proj.weight": "model-00001-of-00004.safetensors",
232
+ "model.layers.2.self_attn.beacon_q_proj.bias": "model-00001-of-00004.safetensors",
233
+ "model.layers.2.self_attn.beacon_q_proj.weight": "model-00001-of-00004.safetensors",
234
+ "model.layers.2.self_attn.beacon_v_proj.bias": "model-00001-of-00004.safetensors",
235
+ "model.layers.2.self_attn.beacon_v_proj.weight": "model-00001-of-00004.safetensors",
236
+ "model.layers.2.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
237
+ "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
238
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
239
+ "model.layers.2.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
240
+ "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
241
+ "model.layers.2.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
242
+ "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
243
+ "model.layers.20.input_layernorm.weight": "model-00003-of-00004.safetensors",
244
+ "model.layers.20.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
245
+ "model.layers.20.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
246
+ "model.layers.20.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
247
+ "model.layers.20.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
248
+ "model.layers.20.self_attn.beacon_k_proj.bias": "model-00003-of-00004.safetensors",
249
+ "model.layers.20.self_attn.beacon_k_proj.weight": "model-00003-of-00004.safetensors",
250
+ "model.layers.20.self_attn.beacon_q_proj.bias": "model-00003-of-00004.safetensors",
251
+ "model.layers.20.self_attn.beacon_q_proj.weight": "model-00003-of-00004.safetensors",
252
+ "model.layers.20.self_attn.beacon_v_proj.bias": "model-00003-of-00004.safetensors",
253
+ "model.layers.20.self_attn.beacon_v_proj.weight": "model-00003-of-00004.safetensors",
254
+ "model.layers.20.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
255
+ "model.layers.20.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
256
+ "model.layers.20.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
257
+ "model.layers.20.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
258
+ "model.layers.20.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
259
+ "model.layers.20.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
260
+ "model.layers.20.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
261
+ "model.layers.21.input_layernorm.weight": "model-00003-of-00004.safetensors",
262
+ "model.layers.21.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
263
+ "model.layers.21.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
264
+ "model.layers.21.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
265
+ "model.layers.21.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
266
+ "model.layers.21.self_attn.beacon_k_proj.bias": "model-00003-of-00004.safetensors",
267
+ "model.layers.21.self_attn.beacon_k_proj.weight": "model-00003-of-00004.safetensors",
268
+ "model.layers.21.self_attn.beacon_q_proj.bias": "model-00003-of-00004.safetensors",
269
+ "model.layers.21.self_attn.beacon_q_proj.weight": "model-00003-of-00004.safetensors",
270
+ "model.layers.21.self_attn.beacon_v_proj.bias": "model-00003-of-00004.safetensors",
271
+ "model.layers.21.self_attn.beacon_v_proj.weight": "model-00003-of-00004.safetensors",
272
+ "model.layers.21.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
273
+ "model.layers.21.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
274
+ "model.layers.21.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
275
+ "model.layers.21.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
276
+ "model.layers.21.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
277
+ "model.layers.21.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
278
+ "model.layers.21.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
279
+ "model.layers.22.input_layernorm.weight": "model-00003-of-00004.safetensors",
280
+ "model.layers.22.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
281
+ "model.layers.22.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
282
+ "model.layers.22.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
283
+ "model.layers.22.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
284
+ "model.layers.22.self_attn.beacon_k_proj.bias": "model-00003-of-00004.safetensors",
285
+ "model.layers.22.self_attn.beacon_k_proj.weight": "model-00003-of-00004.safetensors",
286
+ "model.layers.22.self_attn.beacon_q_proj.bias": "model-00003-of-00004.safetensors",
287
+ "model.layers.22.self_attn.beacon_q_proj.weight": "model-00003-of-00004.safetensors",
288
+ "model.layers.22.self_attn.beacon_v_proj.bias": "model-00003-of-00004.safetensors",
289
+ "model.layers.22.self_attn.beacon_v_proj.weight": "model-00003-of-00004.safetensors",
290
+ "model.layers.22.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
291
+ "model.layers.22.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
292
+ "model.layers.22.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
293
+ "model.layers.22.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
294
+ "model.layers.22.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
295
+ "model.layers.22.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
296
+ "model.layers.22.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
297
+ "model.layers.23.input_layernorm.weight": "model-00003-of-00004.safetensors",
298
+ "model.layers.23.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
299
+ "model.layers.23.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
300
+ "model.layers.23.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
301
+ "model.layers.23.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
302
+ "model.layers.23.self_attn.beacon_k_proj.bias": "model-00003-of-00004.safetensors",
303
+ "model.layers.23.self_attn.beacon_k_proj.weight": "model-00003-of-00004.safetensors",
304
+ "model.layers.23.self_attn.beacon_q_proj.bias": "model-00003-of-00004.safetensors",
305
+ "model.layers.23.self_attn.beacon_q_proj.weight": "model-00003-of-00004.safetensors",
306
+ "model.layers.23.self_attn.beacon_v_proj.bias": "model-00003-of-00004.safetensors",
307
+ "model.layers.23.self_attn.beacon_v_proj.weight": "model-00003-of-00004.safetensors",
308
+ "model.layers.23.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
309
+ "model.layers.23.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
310
+ "model.layers.23.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
311
+ "model.layers.23.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
312
+ "model.layers.23.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
313
+ "model.layers.23.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
314
+ "model.layers.23.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
315
+ "model.layers.24.input_layernorm.weight": "model-00003-of-00004.safetensors",
316
+ "model.layers.24.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
317
+ "model.layers.24.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
318
+ "model.layers.24.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
319
+ "model.layers.24.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
320
+ "model.layers.24.self_attn.beacon_k_proj.bias": "model-00003-of-00004.safetensors",
321
+ "model.layers.24.self_attn.beacon_k_proj.weight": "model-00003-of-00004.safetensors",
322
+ "model.layers.24.self_attn.beacon_q_proj.bias": "model-00003-of-00004.safetensors",
323
+ "model.layers.24.self_attn.beacon_q_proj.weight": "model-00003-of-00004.safetensors",
324
+ "model.layers.24.self_attn.beacon_v_proj.bias": "model-00003-of-00004.safetensors",
325
+ "model.layers.24.self_attn.beacon_v_proj.weight": "model-00003-of-00004.safetensors",
326
+ "model.layers.24.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
327
+ "model.layers.24.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
328
+ "model.layers.24.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
329
+ "model.layers.24.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
330
+ "model.layers.24.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
331
+ "model.layers.24.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
332
+ "model.layers.24.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
333
+ "model.layers.25.input_layernorm.weight": "model-00003-of-00004.safetensors",
334
+ "model.layers.25.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
335
+ "model.layers.25.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
336
+ "model.layers.25.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
337
+ "model.layers.25.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
338
+ "model.layers.25.self_attn.beacon_k_proj.bias": "model-00003-of-00004.safetensors",
339
+ "model.layers.25.self_attn.beacon_k_proj.weight": "model-00003-of-00004.safetensors",
340
+ "model.layers.25.self_attn.beacon_q_proj.bias": "model-00003-of-00004.safetensors",
341
+ "model.layers.25.self_attn.beacon_q_proj.weight": "model-00003-of-00004.safetensors",
342
+ "model.layers.25.self_attn.beacon_v_proj.bias": "model-00003-of-00004.safetensors",
343
+ "model.layers.25.self_attn.beacon_v_proj.weight": "model-00003-of-00004.safetensors",
344
+ "model.layers.25.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
345
+ "model.layers.25.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
346
+ "model.layers.25.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
347
+ "model.layers.25.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
348
+ "model.layers.25.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
349
+ "model.layers.25.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
350
+ "model.layers.25.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
351
+ "model.layers.26.input_layernorm.weight": "model-00003-of-00004.safetensors",
352
+ "model.layers.26.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
353
+ "model.layers.26.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
354
+ "model.layers.26.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
355
+ "model.layers.26.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
356
+ "model.layers.26.self_attn.beacon_k_proj.bias": "model-00003-of-00004.safetensors",
357
+ "model.layers.26.self_attn.beacon_k_proj.weight": "model-00003-of-00004.safetensors",
358
+ "model.layers.26.self_attn.beacon_q_proj.bias": "model-00003-of-00004.safetensors",
359
+ "model.layers.26.self_attn.beacon_q_proj.weight": "model-00003-of-00004.safetensors",
360
+ "model.layers.26.self_attn.beacon_v_proj.bias": "model-00003-of-00004.safetensors",
361
+ "model.layers.26.self_attn.beacon_v_proj.weight": "model-00003-of-00004.safetensors",
362
+ "model.layers.26.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
363
+ "model.layers.26.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
364
+ "model.layers.26.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
365
+ "model.layers.26.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
366
+ "model.layers.26.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
367
+ "model.layers.26.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
368
+ "model.layers.26.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
369
+ "model.layers.27.input_layernorm.weight": "model-00004-of-00004.safetensors",
370
+ "model.layers.27.mlp.down_proj.weight": "model-00004-of-00004.safetensors",
371
+ "model.layers.27.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
372
+ "model.layers.27.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
373
+ "model.layers.27.post_attention_layernorm.weight": "model-00004-of-00004.safetensors",
374
+ "model.layers.27.self_attn.beacon_k_proj.bias": "model-00003-of-00004.safetensors",
375
+ "model.layers.27.self_attn.beacon_k_proj.weight": "model-00003-of-00004.safetensors",
376
+ "model.layers.27.self_attn.beacon_q_proj.bias": "model-00003-of-00004.safetensors",
377
+ "model.layers.27.self_attn.beacon_q_proj.weight": "model-00003-of-00004.safetensors",
378
+ "model.layers.27.self_attn.beacon_v_proj.bias": "model-00003-of-00004.safetensors",
379
+ "model.layers.27.self_attn.beacon_v_proj.weight": "model-00003-of-00004.safetensors",
380
+ "model.layers.27.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
381
+ "model.layers.27.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
382
+ "model.layers.27.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
383
+ "model.layers.27.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
384
+ "model.layers.27.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
385
+ "model.layers.27.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
386
+ "model.layers.27.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
387
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00004.safetensors",
388
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
389
+ "model.layers.3.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
390
+ "model.layers.3.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
391
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
392
+ "model.layers.3.self_attn.beacon_k_proj.bias": "model-00001-of-00004.safetensors",
393
+ "model.layers.3.self_attn.beacon_k_proj.weight": "model-00001-of-00004.safetensors",
394
+ "model.layers.3.self_attn.beacon_q_proj.bias": "model-00001-of-00004.safetensors",
395
+ "model.layers.3.self_attn.beacon_q_proj.weight": "model-00001-of-00004.safetensors",
396
+ "model.layers.3.self_attn.beacon_v_proj.bias": "model-00001-of-00004.safetensors",
397
+ "model.layers.3.self_attn.beacon_v_proj.weight": "model-00001-of-00004.safetensors",
398
+ "model.layers.3.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
399
+ "model.layers.3.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
400
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
401
+ "model.layers.3.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
402
+ "model.layers.3.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
403
+ "model.layers.3.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
404
+ "model.layers.3.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
405
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00004.safetensors",
406
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
407
+ "model.layers.4.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
408
+ "model.layers.4.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
409
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
410
+ "model.layers.4.self_attn.beacon_k_proj.bias": "model-00001-of-00004.safetensors",
411
+ "model.layers.4.self_attn.beacon_k_proj.weight": "model-00001-of-00004.safetensors",
412
+ "model.layers.4.self_attn.beacon_q_proj.bias": "model-00001-of-00004.safetensors",
413
+ "model.layers.4.self_attn.beacon_q_proj.weight": "model-00001-of-00004.safetensors",
414
+ "model.layers.4.self_attn.beacon_v_proj.bias": "model-00001-of-00004.safetensors",
415
+ "model.layers.4.self_attn.beacon_v_proj.weight": "model-00001-of-00004.safetensors",
416
+ "model.layers.4.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
417
+ "model.layers.4.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
418
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
419
+ "model.layers.4.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
420
+ "model.layers.4.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
421
+ "model.layers.4.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
422
+ "model.layers.4.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
423
+ "model.layers.5.input_layernorm.weight": "model-00001-of-00004.safetensors",
424
+ "model.layers.5.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
425
+ "model.layers.5.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
426
+ "model.layers.5.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
427
+ "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
428
+ "model.layers.5.self_attn.beacon_k_proj.bias": "model-00001-of-00004.safetensors",
429
+ "model.layers.5.self_attn.beacon_k_proj.weight": "model-00001-of-00004.safetensors",
430
+ "model.layers.5.self_attn.beacon_q_proj.bias": "model-00001-of-00004.safetensors",
431
+ "model.layers.5.self_attn.beacon_q_proj.weight": "model-00001-of-00004.safetensors",
432
+ "model.layers.5.self_attn.beacon_v_proj.bias": "model-00001-of-00004.safetensors",
433
+ "model.layers.5.self_attn.beacon_v_proj.weight": "model-00001-of-00004.safetensors",
434
+ "model.layers.5.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
435
+ "model.layers.5.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
436
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
437
+ "model.layers.5.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
438
+ "model.layers.5.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
439
+ "model.layers.5.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
440
+ "model.layers.5.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
441
+ "model.layers.6.input_layernorm.weight": "model-00001-of-00004.safetensors",
442
+ "model.layers.6.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
443
+ "model.layers.6.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
444
+ "model.layers.6.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
445
+ "model.layers.6.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
446
+ "model.layers.6.self_attn.beacon_k_proj.bias": "model-00001-of-00004.safetensors",
447
+ "model.layers.6.self_attn.beacon_k_proj.weight": "model-00001-of-00004.safetensors",
448
+ "model.layers.6.self_attn.beacon_q_proj.bias": "model-00001-of-00004.safetensors",
449
+ "model.layers.6.self_attn.beacon_q_proj.weight": "model-00001-of-00004.safetensors",
450
+ "model.layers.6.self_attn.beacon_v_proj.bias": "model-00001-of-00004.safetensors",
451
+ "model.layers.6.self_attn.beacon_v_proj.weight": "model-00001-of-00004.safetensors",
452
+ "model.layers.6.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
453
+ "model.layers.6.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
454
+ "model.layers.6.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
455
+ "model.layers.6.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
456
+ "model.layers.6.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
457
+ "model.layers.6.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
458
+ "model.layers.6.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
459
+ "model.layers.7.input_layernorm.weight": "model-00002-of-00004.safetensors",
460
+ "model.layers.7.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
461
+ "model.layers.7.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
462
+ "model.layers.7.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
463
+ "model.layers.7.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
464
+ "model.layers.7.self_attn.beacon_k_proj.bias": "model-00001-of-00004.safetensors",
465
+ "model.layers.7.self_attn.beacon_k_proj.weight": "model-00001-of-00004.safetensors",
466
+ "model.layers.7.self_attn.beacon_q_proj.bias": "model-00001-of-00004.safetensors",
467
+ "model.layers.7.self_attn.beacon_q_proj.weight": "model-00001-of-00004.safetensors",
468
+ "model.layers.7.self_attn.beacon_v_proj.bias": "model-00001-of-00004.safetensors",
469
+ "model.layers.7.self_attn.beacon_v_proj.weight": "model-00001-of-00004.safetensors",
470
+ "model.layers.7.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
471
+ "model.layers.7.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
472
+ "model.layers.7.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
473
+ "model.layers.7.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
474
+ "model.layers.7.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
475
+ "model.layers.7.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
476
+ "model.layers.7.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
477
+ "model.layers.8.input_layernorm.weight": "model-00002-of-00004.safetensors",
478
+ "model.layers.8.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
479
+ "model.layers.8.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
480
+ "model.layers.8.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
481
+ "model.layers.8.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
482
+ "model.layers.8.self_attn.beacon_k_proj.bias": "model-00002-of-00004.safetensors",
483
+ "model.layers.8.self_attn.beacon_k_proj.weight": "model-00002-of-00004.safetensors",
484
+ "model.layers.8.self_attn.beacon_q_proj.bias": "model-00002-of-00004.safetensors",
485
+ "model.layers.8.self_attn.beacon_q_proj.weight": "model-00002-of-00004.safetensors",
486
+ "model.layers.8.self_attn.beacon_v_proj.bias": "model-00002-of-00004.safetensors",
487
+ "model.layers.8.self_attn.beacon_v_proj.weight": "model-00002-of-00004.safetensors",
488
+ "model.layers.8.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
489
+ "model.layers.8.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
490
+ "model.layers.8.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
491
+ "model.layers.8.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
492
+ "model.layers.8.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
493
+ "model.layers.8.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
494
+ "model.layers.8.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
495
+ "model.layers.9.input_layernorm.weight": "model-00002-of-00004.safetensors",
496
+ "model.layers.9.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
497
+ "model.layers.9.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
498
+ "model.layers.9.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
499
+ "model.layers.9.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
500
+ "model.layers.9.self_attn.beacon_k_proj.bias": "model-00002-of-00004.safetensors",
501
+ "model.layers.9.self_attn.beacon_k_proj.weight": "model-00002-of-00004.safetensors",
502
+ "model.layers.9.self_attn.beacon_q_proj.bias": "model-00002-of-00004.safetensors",
503
+ "model.layers.9.self_attn.beacon_q_proj.weight": "model-00002-of-00004.safetensors",
504
+ "model.layers.9.self_attn.beacon_v_proj.bias": "model-00002-of-00004.safetensors",
505
+ "model.layers.9.self_attn.beacon_v_proj.weight": "model-00002-of-00004.safetensors",
506
+ "model.layers.9.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
507
+ "model.layers.9.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
508
+ "model.layers.9.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
509
+ "model.layers.9.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
510
+ "model.layers.9.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
511
+ "model.layers.9.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
512
+ "model.layers.9.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
513
+ "model.norm.weight": "model-00004-of-00004.safetensors"
514
+ }
515
+ }
modeling_beacon.py ADDED
@@ -0,0 +1,1033 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import time
4
+ import numpy as np
5
+ import torch.distributed as dist
6
+ from transformers.utils import logging
7
+ from transformers import AutoTokenizer
8
+ from itertools import cycle
9
+ from typing import List
10
+
11
+ logger = logging.get_logger(__name__)
12
+
13
+
14
+ class Memory(torch.nn.Module):
15
+ def __init__(
16
+ self,
17
+ model_config,
18
+ k_seq_dim:int=2,
19
+ v_seq_dim:int=2,
20
+ ):
21
+ """Setup necessary attributes."""
22
+ super().__init__()
23
+
24
+ self.config = model_config
25
+
26
+ # initialize necessary parameters
27
+ self.k_seq_dim = k_seq_dim
28
+ self.v_seq_dim = v_seq_dim
29
+ self.rng = np.random.default_rng(42)
30
+
31
+ self.beacon_token = torch.tensor([self.config.vocab_size])
32
+
33
+ self._post_validation()
34
+ self.reset()
35
+
36
+ def _post_validation(self, verbose=True):
37
+ assert self.config.beacon_window >= self.config.beacon_stride, f"Make sure the beacon_window {self.config.beacon_window} >= beacon_stride {self.config.beacon_stride}!"
38
+ for ratio in self.config.beacon_ratio:
39
+ assert ratio >= 0, f"Make sure all beacon ratios are greater than or equal to 0, found {self.config.beacon_ratio}!"
40
+ assert self.config.beacon_attn in ["segmentation", "step-expansion", "full-coverage"], f"beacon_attn {self.config.beacon_attn} not implemented!"
41
+ assert self.config.beacon_ratio_mix in ["instance-random", "step-random", "sequence"] or "adapt-" in self.config.beacon_ratio_mix, f"beacon_ratio_mix {self.config.beacon_ratio_mix} not implemented!"
42
+ # assert self.config.beacon_pos in ["append", "interleave"], f"beacon_pos {self.config.beacon_pos} not implemented!"
43
+ if self.config.beacon_pos == "interleave":
44
+ assert self.config.beacon_window == self.config.beacon_stride, f"Make sure the beacon_window equals to beacon_stride when using interleaving mode."
45
+ if self.config.beacon_parallel_window > 1:
46
+ assert self.config._attn_implementation != "flash_attention_2", f"Currently parallel window does not support flash_attention_2!"
47
+
48
+ self._cpu = torch.device("cpu")
49
+
50
+ if verbose:
51
+ info = f"applying activation beacon on {self.config.beacon_param} (the beacon embedding is initialized from {'bos' if self.config.beacon_embed_init == 'bos' else 'eos'} embedding, the beacon tokens are positioned with '{self.config.beacon_pos}' method), with window size {self.config.beacon_window}, stride {self.config.beacon_stride}, {self.config.beacon_attn} attention{' (attending to previous beacons)' if self.config.beacon_attend_prev else ' (no attending to previous beacons)'}, sink size {self.config.beacon_sink_size}, compression ratio {self.config.beacon_ratio} (mixed by {self.config.beacon_ratio_mix})..."
52
+ logger.info(info)
53
+
54
+ def set(self, verbose=True, **kwargs):
55
+ """
56
+ Set attributes out of the constructor.
57
+ """
58
+ for k, v in kwargs.items():
59
+ setattr(self.config, k, v)
60
+ self._post_validation(verbose=verbose)
61
+
62
+ def reset(self):
63
+ """Initialize attributes for a new sequence."""
64
+ # the cursor pointing to the start of the current window
65
+ self._start_idx = 0
66
+ # the cursor pointing to the end of the current window
67
+ self._end_idx = 0
68
+ # the beacon sizes of all strides
69
+ self._all_beacon_sizes = []
70
+ # the loss per batch
71
+ self._batch_loss = None
72
+ # the valid token number per batch
73
+ self._valid_token_num = None
74
+ # the step index for processing the input_ids
75
+ self._step_idx = 0
76
+ # used in set_compression_ratio
77
+ self._compression_ratio = None
78
+ # the previous inputs is a full window or not, defaults to True
79
+ self._is_full_window = True
80
+ # the number of raw activations to preserve in update_memory (only useful when beacon_stride < beacon_window)
81
+ self._raw_size_to_cache = 0
82
+
83
+ # the number of tokens in previous stride that should be compressed by the upcoming beacon
84
+ self._interleave_remainder = 0
85
+ # compression ratio for the unfinished window
86
+ self._interleave_compression_ratio = None
87
+ self._beacon_indices = None
88
+
89
+ self.all_input_ids = None
90
+ self.all_attention_mask = None
91
+ self.all_labels = None
92
+
93
+ # the raw activations of recent tokens
94
+ self.raw_activations = [(None, None) for _ in range(self.config.num_hidden_layers)]
95
+ # the attention sink activations
96
+ self.sink_activations = [(None, None) for _ in range(self.config.num_hidden_layers)]
97
+ # the beacon activations
98
+ self.beacon_activations = [(None, None) for _ in range(self.config.num_hidden_layers)]
99
+
100
+ @property
101
+ def all_sequence_length(self):
102
+ if self.all_input_ids is None:
103
+ return 0
104
+ else:
105
+ return self.all_input_ids.shape[1]
106
+
107
+ @property
108
+ def batch_size(self):
109
+ if self.all_input_ids is None:
110
+ return 0
111
+ else:
112
+ return self.all_input_ids.shape[0]
113
+
114
+ @property
115
+ def finish(self):
116
+ is_finish = self._end_idx == self.all_sequence_length
117
+ return is_finish
118
+
119
+ @property
120
+ def dtype(self):
121
+ return self.config.torch_dtype
122
+
123
+ @property
124
+ def min_value(self):
125
+ return torch.finfo(self.dtype).min
126
+
127
+ @property
128
+ def max_position_embeddings(self):
129
+ max_position_embeddings = self.config.max_position_embeddings
130
+ if getattr(self.config, "rope_scaling", None) is not None:
131
+ scaling_factor = self.config.rope_scaling["factor"]
132
+ max_position_embeddings = max_position_embeddings * scaling_factor
133
+ return max_position_embeddings
134
+
135
+ def get_memory_size(self):
136
+ """
137
+ Sink memory size, beacon memory size and raw memory size.
138
+ """
139
+ sink_memory_size = 0
140
+ beacon_memory_size = 0
141
+ raw_memory_size = 0
142
+ if self.sink_activations[0][0] is not None:
143
+ sink_memory_size += self.sink_activations[0][0].shape[self.k_seq_dim]
144
+ if self.beacon_activations[0][0] is not None:
145
+ beacon_memory_size += self.beacon_activations[0][0].shape[self.k_seq_dim]
146
+ if self.raw_activations[0][0] is not None:
147
+ raw_memory_size += self.raw_activations[0][0].shape[self.k_seq_dim]
148
+ return sink_memory_size, beacon_memory_size, raw_memory_size
149
+
150
+ def prepare(self, input_ids, attention_mask, labels):
151
+ """
152
+ Prepare inputs for the model. These inputs belong to the same sequence.
153
+ """
154
+ # assert input_ids.shape[0] == 1, "Make sure the batch size is 1!"
155
+ # assert attention_mask is None or (attention_mask == 1).all(), "Make sure there is no padding!"
156
+
157
+ self._device = input_ids.device
158
+
159
+ # accumulate input_ids
160
+ if self.all_input_ids is None:
161
+ self.all_input_ids = input_ids.cpu()
162
+ else:
163
+ self.all_input_ids = torch.cat([self.all_input_ids, input_ids.cpu()], dim=1)
164
+
165
+ # accumulate attention_mask
166
+ if attention_mask is None:
167
+ attention_mask = torch.ones_like(input_ids, device=torch.device("cpu"))
168
+ if self.all_attention_mask is None:
169
+ self.all_attention_mask = attention_mask.cpu()
170
+ else:
171
+ self.all_attention_mask = torch.cat([self.all_attention_mask, attention_mask.cpu()], dim=1)
172
+
173
+ # accumulate labels if exisits
174
+ if labels is not None:
175
+ # rotate labels in advance so that the loss of the last token is not ignored in every window
176
+ labels = torch.cat([labels[:, 1:].cpu(), torch.tensor([-100]).expand(labels.shape[0], 1)], dim=1)
177
+ if self.all_labels is None:
178
+ self.all_labels = labels.cpu()
179
+ else:
180
+ self.all_labels = torch.cat([self.all_labels, labels], dim=1)
181
+ assert self.all_input_ids.shape[1] == self.all_labels.shape[1], f"Found inconsistent all_input_ids {self.all_input_ids.shape} and all_labels {self.all_labels.shape}!"
182
+
183
+ def set_compression_ratio(self, start_idx, end_idx):
184
+ """Choose a condensing ratio from self.config.beacon_ratio"""
185
+ def filter_ratio(ratios, stride):
186
+ valid_ratios = []
187
+ for ratio in ratios:
188
+ # stride must be bigger than condensing ratio because we there must be at least one beacon
189
+ if stride < ratio:
190
+ continue
191
+ # the stride must be evenly divisible by condensing ratio
192
+ if ratio > 0 and (stride % ratio) != 0:
193
+ continue
194
+ # when training, ratio=0 is valid if previous windows contain beacon or later windows contain beacon
195
+ if ratio == 0 and self.training:
196
+ previous_has_zero = -1 in self._all_beacon_sizes
197
+ following_has_nonzero = (start_idx + stride + self.config.beacon_window) <= self.all_sequence_length
198
+ if previous_has_zero or (not following_has_nonzero):
199
+ continue
200
+ valid_ratios.append(ratio)
201
+ assert len(valid_ratios), f"Cannot find valid condensing ratio (among {ratios}) for stride {stride}!"
202
+ return valid_ratios
203
+
204
+ def get_max_length(ratios):
205
+ max_lengths = []
206
+ for compression_ratio in ratios:
207
+ if compression_ratio > 0:
208
+ # NOTE: here we must use the scaled position embeddings
209
+ max_lengths.append((self.max_position_embeddings - self.config.beacon_window) * compression_ratio + self.config.beacon_window)
210
+ else:
211
+ max_lengths.append(self.max_position_embeddings)
212
+ return max_lengths
213
+
214
+ if len(self.config.beacon_ratio) == 1:
215
+ return self.config.beacon_ratio[0]
216
+
217
+ ratio_mix = self.config.beacon_ratio_mix
218
+
219
+ beacon_ratio = filter_ratio(self.config.beacon_ratio, self.config.beacon_stride)
220
+
221
+ if ratio_mix == "instance-random":
222
+ if self._compression_ratio is None:
223
+ beacon_ratio = self.rng.choice(beacon_ratio).tolist()
224
+ self._compression_ratio = beacon_ratio
225
+ else:
226
+ beacon_ratio = self._compression_ratio
227
+
228
+ elif ratio_mix == "step-random":
229
+ beacon_ratio = self.rng.choice(beacon_ratio).tolist()
230
+
231
+ elif ratio_mix == "sequence":
232
+ if self._compression_ratio is None:
233
+ self._compression_ratio = cycle(beacon_ratio)
234
+ beacon_ratio = next(self._compression_ratio)
235
+
236
+ elif "adapt" in ratio_mix:
237
+ if self._compression_ratio is None:
238
+ future_length = int(ratio_mix.split("-")[1])
239
+ sequence_length = self.all_input_ids.shape[1] + future_length
240
+ max_lengths = get_max_length(beacon_ratio)
241
+ # ascendingly sort the max lengths
242
+ valid_max_lengths_and_indices = [x for x in enumerate(max_lengths) if x[1] >= sequence_length]
243
+ if len(valid_max_lengths_and_indices):
244
+ minimum_length_index = min(valid_max_lengths_and_indices, key=lambda x: x[1])[0]
245
+ # use the minimal possible length for this sequence (the smallest fold ratio)
246
+ beacon_ratio = beacon_ratio[minimum_length_index]
247
+ else:
248
+ beacon_ratio = max(beacon_ratio)
249
+ # logger.warning(f"Failed to find valid fold window and size for sequence length {sequence_length}, as the maximum theoretical length is {max(max_lengths)}. Fall back to use the maximum one: {beacon_ratio}.")
250
+ self._compression_ratio = beacon_ratio
251
+ else:
252
+ beacon_ratio = self._compression_ratio
253
+
254
+ return beacon_ratio
255
+
256
+ def step(self):
257
+ # parallel does not support stride < window
258
+ # parallel does not support non-compression
259
+ # the input_ids is not long enough for parallel
260
+ if \
261
+ (self.config.beacon_parallel_window > 1) and \
262
+ (self.config.beacon_stride == self.config.beacon_window) and \
263
+ (0 not in self.config.beacon_ratio) and \
264
+ (self.all_input_ids[:, self._end_idx:].shape[1] >= self.config.beacon_parallel_window * self.config.beacon_window):
265
+ input_ids_list = []
266
+ attention_mask_list = []
267
+ position_ids_list = []
268
+ labels_list = []
269
+
270
+ beacon_size_list = []
271
+ beacon_indices_list = []
272
+
273
+ for i in range(self.config.beacon_parallel_window):
274
+ if i == 0:
275
+ _input_ids, _attention_mask, _position_ids, _past_key_values, _labels = self._step()
276
+ else:
277
+ _input_ids, _attention_mask, _position_ids, _past_key_values, _labels = self._step(ignore_memory=True)
278
+
279
+ input_ids_list.append(_input_ids)
280
+ attention_mask_list.append(_attention_mask)
281
+ position_ids_list.append(_position_ids)
282
+ labels_list.append(_labels)
283
+ beacon_size_list.append(_past_key_values[0][2])
284
+ beacon_indices_list.append(_past_key_values[0][3])
285
+
286
+ if i == 0:
287
+ past_key_values = _past_key_values
288
+ if past_key_values[0][0] is None:
289
+ mem_size = 0
290
+ else:
291
+ mem_size = past_key_values[0][0].shape[self.k_seq_dim]
292
+
293
+ else:
294
+ # no memory
295
+ assert _past_key_values[0][0] is None
296
+
297
+ batch_size = self.all_input_ids.shape[0]
298
+ # NOTE: we do not need to repliace beacon tokens for the last window
299
+ seq_len = sum(x.shape[1] for x in input_ids_list) + sum(beacon_size_list) - beacon_size_list[-1]
300
+
301
+ input_ids = _input_ids.new_zeros((batch_size, seq_len)) + self.beacon_token.to(_input_ids.device)
302
+ # all 0
303
+ attention_mask = _attention_mask.new_zeros((batch_size, 1, seq_len, mem_size + seq_len)) + self.min_value
304
+ position_ids = torch.arange(mem_size + seq_len, device=self._device).expand(batch_size, mem_size + seq_len)
305
+ # 2 indicates the beacon token is used for replication
306
+ beacon_indices = beacon_indices_list[0].new_zeros(seq_len) + 2
307
+ if _labels is not None:
308
+ # -100 because no loss on beacon tokens
309
+ labels = _labels.new_zeros((batch_size, seq_len)) - 100
310
+ else:
311
+ labels = None
312
+
313
+ start_idx = 0
314
+ position_offset = mem_size
315
+ for i in range(self.config.beacon_parallel_window):
316
+ beacon_size = beacon_size_list[i]
317
+
318
+ # populate input_ids
319
+ _input_ids = input_ids_list[i]
320
+ cur_seq_len = _input_ids.shape[1]
321
+ input_ids[:, start_idx: start_idx + cur_seq_len] = _input_ids
322
+
323
+ # populate attention_mask and position_ids
324
+ _attention_mask = attention_mask_list[i]
325
+ _position_ids = position_ids_list[i]
326
+ # the attention mask in the first window contains the mask for memory, which is redundant here
327
+ if i == 0:
328
+ _attention_mask = _attention_mask[:, :, :, mem_size:]
329
+ _position_ids = _position_ids[:, mem_size:] - mem_size
330
+
331
+ attention_mask[:, :, start_idx: start_idx + cur_seq_len, mem_size + start_idx: mem_size + start_idx + cur_seq_len] = _attention_mask
332
+ position_ids[:, mem_size + start_idx: mem_size + start_idx + cur_seq_len] = _position_ids + position_offset
333
+
334
+ # populate beacon_indices
335
+ _beacon_indices = beacon_indices_list[i]
336
+ beacon_indices[start_idx: start_idx + cur_seq_len] = _beacon_indices
337
+
338
+ # populate labels
339
+ if labels is not None:
340
+ # populate labels
341
+ _labels = labels_list[i]
342
+ labels[:, start_idx: start_idx + cur_seq_len] = _labels
343
+
344
+ # NOTE: when there is sink activations, we need to bias the position_ids for the first window
345
+ if i == 0 and self.config.beacon_sink_size > 0 and self.sink_activations[0][0] is None:
346
+ position_offset += 1
347
+
348
+ # modify the attention and position for replicated beacon tokens
349
+ if i != self.config.beacon_parallel_window - 1:
350
+ replicate_beacon_row_start = start_idx + cur_seq_len
351
+ replicate_beacon_col_start = mem_size + start_idx + cur_seq_len
352
+ # NOTE: any attention mask is okay for replicated beacon tokens, but for convenience we use the causal mask
353
+ attention_mask[:, :, replicate_beacon_row_start: replicate_beacon_row_start + beacon_size, replicate_beacon_col_start: replicate_beacon_col_start + beacon_size] = _attention_mask.new_full((beacon_size, beacon_size), self.min_value).triu(1)
354
+ # NOTE: all future tokens can attend to the replicated beacon tokens
355
+ attention_mask[:, :, replicate_beacon_row_start + beacon_size:, replicate_beacon_col_start: replicate_beacon_col_start + beacon_size] = 0
356
+ # NOTE: the position of replicated beacon tokens start from 0
357
+ position_ids[:, mem_size + start_idx + cur_seq_len: mem_size + start_idx + cur_seq_len + beacon_size] = torch.arange(position_offset, position_offset + beacon_size, device=_input_ids.device)[None:]
358
+
359
+ start_idx += cur_seq_len + beacon_size
360
+ position_offset += beacon_size
361
+
362
+ # the memory is visible to all subsequent tokens
363
+ attention_mask[:, :, :, :max(mem_size, self.config.beacon_sink_size)] = 0
364
+
365
+ # NOTE: modify beacon_indices
366
+ for i, (key, value, _, _) in enumerate(past_key_values):
367
+ past_key_values[i] = (key, value, sum(beacon_size_list), beacon_indices)
368
+
369
+ # NOTE: update _beacon_indices so that the next-token logits can be properly sliced out in self.output()
370
+ self._beacon_indices = beacon_indices
371
+
372
+ return input_ids, attention_mask, position_ids, past_key_values, labels
373
+
374
+ else:
375
+ return self._step()
376
+
377
+ def _step(self, ignore_memory=False):
378
+ """
379
+ Yield inputs for the current sliding window, including the input_ids, attention_mask, position_ids, and past_key_values.
380
+ """
381
+ #============================================#
382
+ # Check whether the inputs fulfills a window.
383
+ #============================================#
384
+
385
+ # the starting position of the current window w.r.t. the start of the current input sequence
386
+ start_idx = self._start_idx
387
+ # the end position of the current window w.r.t. the start of the current input sequence
388
+ end_idx = start_idx + self.config.beacon_window
389
+ # indicates if the current window is completely filled by raw activations and new tokens
390
+ # we only append beacon tokens for full windows
391
+ if end_idx > self.all_sequence_length:
392
+ # the input is shorter than the initial window size
393
+ end_idx = self.all_sequence_length
394
+ is_full_window = False
395
+ else:
396
+ is_full_window = True
397
+
398
+ # NOTE: in training, the entire sequence is input to the model at once
399
+ # In the last window, we do not need to append beacons because they will not be used at all
400
+ if self.training and end_idx == self.all_sequence_length:
401
+ next_start_idx = start_idx
402
+ raw_size_to_cache = -1
403
+ beacon_size = 0
404
+ compression_ratio = 1
405
+ is_full_window = False
406
+
407
+ else:
408
+ #============================================#
409
+ # Set compression ratio
410
+ #============================================#
411
+ if self.config.beacon_pos == "append":
412
+ if is_full_window:
413
+ # determine compression ratio for the current window
414
+ beacon_stride = self.config.beacon_stride
415
+ compression_ratio = self.set_compression_ratio(start_idx=start_idx, end_idx=end_idx)
416
+
417
+ if compression_ratio > 0:
418
+ # the stride must be evenly divisible by compression_ratio
419
+ beacon_size = beacon_stride // compression_ratio
420
+ else:
421
+ # the raw activations are used as beacon activations
422
+ beacon_size = -1
423
+
424
+ # forward start_idx and end_idx
425
+ next_start_idx = start_idx + beacon_stride
426
+ # how many raw activations to save
427
+ raw_size_to_cache = end_idx - next_start_idx
428
+ else:
429
+ # no stride because the sequence has finished
430
+ next_start_idx = start_idx
431
+ # cache all raw activations
432
+ raw_size_to_cache = -1
433
+ beacon_size = 0
434
+ compression_ratio = 0
435
+
436
+ elif self.config.beacon_pos == "interleave":
437
+ # the number of raw tokens in the input_ids
438
+ input_size = end_idx - self._end_idx
439
+ # set compression ratio once the previous window has finished, otherwise, reuse the interleave_compression_ratio if the input belongs to an unfinished window
440
+ if self._is_full_window:
441
+ compression_ratio = self.set_compression_ratio(start_idx=start_idx, end_idx=end_idx)
442
+ self._interleave_compression_ratio = compression_ratio
443
+ else:
444
+ compression_ratio = self._interleave_compression_ratio
445
+
446
+ # the beacon size is non-zero even if the window is not full
447
+ if compression_ratio > 0:
448
+ # this number of beacon tokens will be inserted among the raw tokens
449
+ beacon_size = (input_size + self._interleave_remainder) // compression_ratio
450
+ else:
451
+ # the raw activations are used as beacon activations
452
+ beacon_size = -1
453
+
454
+ if is_full_window:
455
+ # move forward one window
456
+ next_start_idx = start_idx + self.config.beacon_stride
457
+ # no save raw activations
458
+ raw_size_to_cache = 0
459
+ else:
460
+ # no stride because the sequence has not finished
461
+ next_start_idx = start_idx
462
+ # cache all recent raw activations to be used in the next window
463
+ raw_size_to_cache = -1
464
+
465
+ #============================================#
466
+ # Slice out input_ids (raw tokens in the current window)
467
+ #============================================#
468
+ input_ids = self.all_input_ids[:, self._end_idx: end_idx].to(self._device)
469
+ attention_mask = self.all_attention_mask[:, self._end_idx: end_idx].to(self._device)
470
+ if self.all_labels is not None:
471
+ labels = self.all_labels[:, self._end_idx: end_idx].to(self._device)
472
+ else:
473
+ labels = None
474
+ batch_size = input_ids.shape[0]
475
+
476
+ #============================================#
477
+ # Insert beacon tokens if necessary.
478
+ #============================================#
479
+ # t1 = time.time()
480
+
481
+ if self.config.beacon_pos == "append":
482
+ # append beacons if necessary
483
+ if is_full_window and beacon_size > 0:
484
+ input_ids = torch.cat([input_ids, self.beacon_token.expand(batch_size, beacon_size).to(input_ids.device, dtype=input_ids.dtype)], dim=1)
485
+ # NOTE: prepend 1 to attention_mask because we have past_key_values
486
+ attention_mask = torch.cat([attention_mask, attention_mask.new_ones(batch_size, beacon_size)], dim=1)
487
+ if labels is not None:
488
+ labels = torch.cat([labels, labels.new_zeros(batch_size, beacon_size) - 100], dim=1)
489
+
490
+ elif self.config.beacon_pos == "interleave":
491
+ input_len = input_ids.shape[1]
492
+ if beacon_size > 0:
493
+ # insert beacon tokens in between raw tokens
494
+ input_ids_with_beacons = input_ids.new_full((input_ids.shape[0], input_len + beacon_size), self.beacon_token.item())
495
+ raw_token_indices = torch.arange(input_ids_with_beacons.shape[1], device=input_ids.device)
496
+ interleave_start_idx = compression_ratio - self._interleave_remainder
497
+ raw_token_indices = raw_token_indices[raw_token_indices % (compression_ratio + 1) != interleave_start_idx].unsqueeze(0).expand_as(input_ids)
498
+ input_ids_with_beacons = input_ids_with_beacons.scatter(dim=1, index=raw_token_indices, src=input_ids)
499
+ input_ids = input_ids_with_beacons
500
+ # attention mask
501
+ attention_mask_with_beacons = attention_mask.new_full((attention_mask.shape[0], attention_mask.shape[1] + beacon_size), 1)
502
+ attention_mask_with_beacons = attention_mask_with_beacons.scatter(dim=1, index=raw_token_indices, src=attention_mask)
503
+ attention_mask = attention_mask_with_beacons
504
+ # labels
505
+ if labels is not None:
506
+ labels_with_beacons = labels.new_full((labels.shape[0], labels.shape[1] + beacon_size), -100)
507
+ labels_with_beacons = labels_with_beacons.scatter(dim=1, index=raw_token_indices, src=labels)
508
+ labels = labels_with_beacons
509
+
510
+ if compression_ratio > 0:
511
+ # update the reminder
512
+ self._interleave_remainder = (input_len + self._interleave_remainder) % compression_ratio
513
+
514
+ # NOTE: skip computing loss in the very first window because the beacon tokens will be used in the next window
515
+ if self.training and self._step_idx == 0 and not (self.config.beacon_pos == 'interleave' and self.config.beacon_attn == 'full-coverage'):
516
+ labels[:] = -100
517
+
518
+ # t2 = time.time()
519
+
520
+ #============================================#
521
+ # Prepare beacon_indices for interleave beacon_pos, a boolean mask where True indicates the beacon tokens.
522
+ # The mask is applied on the inputs of the entire window, including the cached activations and the input_ids.
523
+ #============================================#
524
+ beacon_indices = (input_ids[0] == self.beacon_token.item()).long()
525
+ if self._is_full_window:
526
+ self._beacon_indices = torch.tensor([], dtype=torch.long, device=input_ids.device)
527
+ # the beacon_indices always tracks the beacon tokens in both the cached activations and the input_ids
528
+ beacon_indices = torch.cat([self._beacon_indices, beacon_indices])
529
+ # record the beacon_indices for the next window
530
+ self._beacon_indices = beacon_indices
531
+ if is_full_window and beacon_size == -1:
532
+ # NOTE: the first beacon_stride raw tokens serve as beacon tokens
533
+ # we use -1 to indicate these raw tokens, so that the attention mask and position ids will not be modified
534
+ beacon_indices[:self.config.beacon_stride] = -1
535
+
536
+ # t3 = time.time()
537
+
538
+ #============================================#
539
+ # Prepare past_key_values.
540
+ # beacon_size: how many beacon tokens are there in the input_ids
541
+ # beacon_indices: the boolean mask for the entire window where True indicates the beacon tokens (for append, the beacon_indices corresponds to input_ids, while for 'interleave', the beacon_indices corresponds to the entire window including both the input_ids and the cached activations)
542
+ #============================================#
543
+ past_key_values = []
544
+ for layer_idx in range(self.config.num_hidden_layers):
545
+ if ignore_memory:
546
+ key, value = None, None
547
+ else:
548
+ sink_key, sink_value = self.sink_activations[layer_idx]
549
+ beacon_key, beacon_value = self.beacon_activations[layer_idx]
550
+ raw_key, raw_value = self.raw_activations[layer_idx]
551
+
552
+ key = cat_tensor([
553
+ sink_key, beacon_key, raw_key,
554
+ ], dim=self.k_seq_dim)
555
+ value = cat_tensor([
556
+ sink_value, beacon_value, raw_value,
557
+ ], dim=self.v_seq_dim)
558
+
559
+ layer_past_key_values = (key, value, beacon_size, beacon_indices)
560
+ past_key_values.append(layer_past_key_values)
561
+
562
+ # t4 = time.time()
563
+
564
+ #============================================#
565
+ # Prepare attention_mask and position_ids.
566
+ #============================================#
567
+ first_key = past_key_values[0][0]
568
+ mem_size = first_key.shape[self.k_seq_dim] if first_key is not None else 0
569
+ if mem_size > 0:
570
+ attention_mask = torch.cat([attention_mask.new_ones(batch_size, mem_size), attention_mask], dim=1)
571
+
572
+ input_length = input_ids.shape[1]
573
+ position_ids = torch.arange(attention_mask.shape[-1], dtype=torch.long, device=self._device).repeat(batch_size, 1)
574
+
575
+ if self.config._attn_implementation == "flash_attention_2":
576
+ assert self.config.beacon_attn == "full-coverage", f"Make sure to set beacon_attn='full-coverage' when using flash attention! Found {self.config.beacon_attn}."
577
+ if 0 in attention_mask:
578
+ pass
579
+ else:
580
+ attention_mask = None
581
+ elif self.config._attn_implementation == "sdpa" and self.config.beacon_pos == "append" and beacon_size <= 0 and (input_length == 1 or mem_size == 0):
582
+ attention_mask = None
583
+ else:
584
+ attention_mask, position_ids = self._make_4d_attention_mask_and_position_ids(
585
+ attention_mask,
586
+ position_ids,
587
+ mem_size,
588
+ beacon_size,
589
+ compression_ratio,
590
+ )
591
+
592
+ # t5 = time.time()
593
+
594
+ # print(f"prepare inputs {t2-t1}, prepare indices {t3-t2}, prepare memory {t4-t3}, prepare attention mask {t5-t4}")
595
+
596
+ #============================================#
597
+ # Update necessary attributes.
598
+ #============================================#
599
+ # keep track of whether the current inputs is a full_window
600
+ self._is_full_window = is_full_window
601
+ # keep track of the raw_size_to_cache
602
+ self._raw_size_to_cache = raw_size_to_cache
603
+ # involked in self.output()
604
+ self._all_beacon_sizes.append(beacon_size)
605
+ # update end_idx
606
+ self._start_idx = next_start_idx
607
+ self._end_idx = end_idx
608
+ self._step_idx += 1
609
+
610
+ # print(f"beacon_size: {beacon_size}")
611
+ # print(f"raw_size_to_cache: {raw_size_to_cache}")
612
+ # print(f"input_ids: {input_ids}")
613
+ # print(f"beacon_indices: {beacon_indices}")
614
+ # print(f"position_ids: {position_ids}")
615
+ # print(f"attention_mask:\n{attention_mask}")
616
+ # x = input()
617
+ # if x == "s":
618
+ # return
619
+
620
+ return input_ids, attention_mask, position_ids, past_key_values, labels
621
+
622
+ def update_memory(self, past_key_values):
623
+ """
624
+ Accumulate beacon activations and raw activations.
625
+ """
626
+ for layer_idx, (key, value, beacon_size, beacon_indices) in enumerate(past_key_values):
627
+ # NOTE: the past_key_values are incrementally returned (only the new keys and values are returned)
628
+ previous_raw_key, previous_raw_value = self.raw_activations[layer_idx]
629
+
630
+ if self.beacon_activations[layer_idx][0] is None and self.config.beacon_sink_size > 0:
631
+ # save the sink activations
632
+ # NOTE: we do not slice the key/value activations, which may cause duplication when beacon_ratio=-1 for the first window, but it's okay
633
+ self.sink_activations[layer_idx] = [
634
+ slice_tensor(key, end=self.config.beacon_sink_size, dim=self.k_seq_dim),
635
+ slice_tensor(value, end=self.config.beacon_sink_size, dim=self.v_seq_dim),
636
+ ]
637
+
638
+ if not self._is_full_window:
639
+ # this means the current input does not fulfill a window
640
+ # thus, the key and value are all raw activations, and we accumulate them until the window is fulfilled
641
+ assert self._raw_size_to_cache == -1
642
+ raw_key = cat_tensor([
643
+ previous_raw_key,
644
+ key
645
+ ], dim=self.k_seq_dim)
646
+ raw_value = cat_tensor([
647
+ previous_raw_value,
648
+ value
649
+ ], dim=self.v_seq_dim)
650
+ self.raw_activations[layer_idx] = (raw_key, raw_value)
651
+
652
+ else:
653
+ # NOTE: use the correct previous_beacon_key and value!
654
+ previous_beacon_key, previous_beacon_value = self.beacon_activations[layer_idx]
655
+
656
+ beacon_key, beacon_value, raw_key, raw_value = self._extract_beacon_and_raw_memory(
657
+ key,
658
+ value,
659
+ previous_beacon_key,
660
+ previous_beacon_value,
661
+ previous_raw_key,
662
+ previous_raw_value,
663
+ beacon_indices,
664
+ )
665
+
666
+ self.beacon_activations[layer_idx] = (beacon_key, beacon_value)
667
+ self.raw_activations[layer_idx] = (raw_key, raw_value)
668
+
669
+ def update_loss(self, batch_loss, valid_token_num):
670
+ """
671
+ Accumulate loss for later perplexity computation and backward pass.
672
+ """
673
+ if self._batch_loss is None:
674
+ # NOTE: multiply valid_token_num because batch_loss is divided by it in advance
675
+ self._batch_loss = batch_loss * valid_token_num
676
+ self._valid_token_num = valid_token_num
677
+ else:
678
+ # NOTE: avoid in-place operations, otherwise there will be gradient errors in training
679
+ self._batch_loss = self._batch_loss + batch_loss * valid_token_num
680
+ self._valid_token_num = self._valid_token_num + valid_token_num
681
+
682
+ def output(self, model_outputs):
683
+ """
684
+ Override loss with accumulated loss. Update the next-token logits.
685
+ """
686
+ # override loss
687
+ if self._batch_loss is not None:
688
+ # here the batch_loss is the summation of all token losses in each element
689
+ loss = self._batch_loss.sum() / self._valid_token_num.sum()
690
+
691
+ # NOTE: prevent nan
692
+ batch_loss = self._batch_loss / self._valid_token_num
693
+ if (self._valid_token_num == 0).any():
694
+ batch_loss = batch_loss.masked_fill(self._valid_token_num == 0, 0.)
695
+
696
+ # NOTE: we must use dict to override values, otherwise trainer cannot find loss
697
+ model_outputs["loss"] = loss
698
+ model_outputs["batch_loss"] = batch_loss
699
+ model_outputs["valid_token_num"] = self._valid_token_num
700
+
701
+ # override last_hidden_states (used in generation)
702
+ beacon_size = self._all_beacon_sizes[-1]
703
+ # remove logits corresponding to beacon tokens
704
+ if beacon_size > 0:
705
+ logits = model_outputs["logits"]
706
+ beacon_indices = self._beacon_indices[-logits.shape[1]:]
707
+ model_outputs["logits"] = logits[:, beacon_indices == 0]
708
+
709
+ return model_outputs
710
+
711
+ def _make_4d_attention_mask_and_position_ids(
712
+ self,
713
+ attention_mask,
714
+ position_ids,
715
+ mem_size,
716
+ beacon_size,
717
+ compression_ratio,
718
+ ):
719
+ """
720
+ Convert attention_mask into causal 4D attention_mask (batch_size, head_num, query_len, key_len).
721
+ """
722
+ tgt_size = attention_mask.size(-1) - mem_size
723
+ dtype = self.dtype
724
+ min_value = self.min_value
725
+ device = self._device
726
+ batch_size, src_size = attention_mask.size()
727
+
728
+ # square for memory, and lower triangular for input_ids
729
+ causal_mask = torch.full((tgt_size, tgt_size), min_value, device=device, dtype=dtype)
730
+ mask_cond = torch.arange(causal_mask.size(-1), device=device)
731
+ causal_mask.masked_fill_(mask_cond < (mask_cond + 1).view(causal_mask.size(-1), -1), 0)
732
+ causal_mask = torch.cat([torch.zeros(tgt_size, mem_size, dtype=dtype, device=device), causal_mask], dim=-1)
733
+ causal_mask = causal_mask[None, None, ...].expand(batch_size, 1, tgt_size, src_size)
734
+ # 1 for non-padding tokens
735
+ expand_mask = attention_mask[:, None, None, :].expand(batch_size, 1, tgt_size, src_size)
736
+ invert_mask = 1.0 - expand_mask
737
+ invert_mask.masked_fill_(invert_mask.bool(), min_value)
738
+
739
+ attention_mask = causal_mask.masked_fill(invert_mask.bool(), min_value)
740
+
741
+ if self.config.beacon_attn == "step-expansion":
742
+ # each beacon can attend to one more sub-interval than its predecessor
743
+
744
+ if self.config.beacon_pos == "append" and beacon_size > 0:
745
+ window_size = self.config.beacon_window
746
+ window_size_with_beacon = window_size + beacon_size
747
+ beacon_start_idx = -beacon_size
748
+ # batch_size, head_num, window_size
749
+ reference_attention_mask = attention_mask[..., -beacon_size - 1, -window_size_with_beacon: -beacon_size]
750
+
751
+ # compression_ratio, 2 * compression_ratio, ..., beacon_size * compression_ratio
752
+ beacon_arange = torch.arange(1, beacon_size + 1, device=device) * compression_ratio
753
+ # 0, 1, 2, ..., window_size - 1
754
+ ordinal_arange = torch.arange(window_size, device=device)
755
+ # beacon_size, window_size
756
+ valid_pos = ordinal_arange.expand(beacon_size, window_size) < beacon_arange.unsqueeze(-1)
757
+ # beacon_size, window_size
758
+ ordinal_attention_mask = torch.where(valid_pos, 0, min_value)
759
+ # NOTE: add reference attention_mask so that padding tokens are considered
760
+ ordinal_attention_mask = ordinal_attention_mask[None, None, ...] + reference_attention_mask.unsqueeze(-2)
761
+
762
+ if self.config.beacon_attend_prev:
763
+ beacon_attention_mask = attention_mask.new_full((beacon_size, beacon_size), min_value).triu(1)
764
+ # the beacon token is next to the last ordinal token it attends to
765
+ ordinal_position_ids = position_ids[:, -window_size_with_beacon: -beacon_size]
766
+ beacon_position_ids = ordinal_position_ids[:, compression_ratio - 1::compression_ratio] + torch.arange(1, beacon_size + 1, device=device)[None]
767
+ position_ids[:, beacon_start_idx:] = beacon_position_ids
768
+ else:
769
+ beacon_attention_mask = attention_mask.new_full((beacon_size, beacon_size), min_value).fill_diagonal_(0)
770
+ # the beacon token is next to the last ordinal token it attends to
771
+ ordinal_position_ids = position_ids[:, -window_size_with_beacon: -beacon_size]
772
+ beacon_position_ids = ordinal_position_ids[:, compression_ratio - 1::compression_ratio] + 1
773
+ position_ids[:, beacon_start_idx:] = beacon_position_ids
774
+
775
+ attention_mask[..., beacon_start_idx:, -window_size_with_beacon: -beacon_size] = ordinal_attention_mask
776
+ attention_mask[..., beacon_start_idx:, beacon_start_idx:] = beacon_attention_mask
777
+
778
+ # NOTE: the attention mask should be modified when there is beacon token within the window, not in the input_ids
779
+ elif self.config.beacon_pos == "interleave" and (self._beacon_indices == 1).any():
780
+ assert self.config.beacon_attend_prev == False, f"Make sure beacon_attend_prev is False if using 'interleave' beacon pos!"
781
+
782
+ beacon_indices = self._beacon_indices
783
+
784
+ cur_position_ids = position_ids[:, -len(beacon_indices):]
785
+ base_position = cur_position_ids[:, 0] - 1
786
+ # NOTE: alternate position so that the position of raw tokens are consistent
787
+ position_template = cur_position_ids.new_ones(cur_position_ids.shape)
788
+ position_template[:, compression_ratio + 1::compression_ratio + 1] = 0
789
+ cur_position_ids = base_position + position_template.cumsum(-1)
790
+ position_ids[:, -len(beacon_indices):] = cur_position_ids
791
+
792
+ cur_input_length = len(beacon_indices)
793
+ cur_attention_mask = attention_mask[..., -cur_input_length:, -cur_input_length:]
794
+ # mask all beacon columns
795
+ cur_attention_mask[..., beacon_indices] = min_value
796
+ # beacon tokens can attend to themselves
797
+ input_ids_attention_mask = cur_attention_mask[..., -tgt_size:, -tgt_size:]
798
+ input_ids_attention_mask[..., range(tgt_size), range(tgt_size)] = 0
799
+
800
+ elif self.config.beacon_attn == "segmentation":
801
+ # each beacon can attend to its corresponding sub-interval
802
+
803
+ if self.config.beacon_pos == "append" and beacon_size > 0:
804
+ window_size = self.config.beacon_window
805
+ window_size_with_beacon = window_size + beacon_size
806
+ beacon_start_idx = -beacon_size
807
+ # batch_size, head_num, window_size
808
+ reference_attention_mask = attention_mask[..., -beacon_size - 1, -window_size_with_beacon: -beacon_size]
809
+
810
+ # beacon_size, compression_ratio
811
+ indices = torch.arange(compression_ratio * beacon_size, device=device).view(beacon_size, -1)
812
+ # beacon_size, window_size
813
+ ordinal_attention_mask = attention_mask.new_full((beacon_size, window_size), min_value)
814
+ ordinal_attention_mask.scatter_(dim=-1, index=indices, value=0)
815
+
816
+ # NOTE: add reference attention_mask so that padding tokens are considered
817
+ ordinal_attention_mask = ordinal_attention_mask[None, None, ...] + reference_attention_mask.unsqueeze(-2)
818
+
819
+ if self.config.beacon_attend_prev:
820
+ beacon_attention_mask = attention_mask.new_full((beacon_size, beacon_size), min_value).triu(1)
821
+ # the beacon token is next to the last ordinal token it attends to
822
+ beacon_position_ids = position_ids.new_full(beacon_size, fill_value=compression_ratio + mem_size)
823
+ beacon_position_ids = beacon_position_ids + torch.arange(beacon_size)
824
+ position_ids[:, beacon_start_idx:] = beacon_position_ids
825
+ else:
826
+ beacon_attention_mask = attention_mask.new_full((beacon_size, beacon_size), min_value).fill_diagonal_(0)
827
+ # the beacon token is next to the last ordinal token it attends to
828
+ beacon_position_ids = position_ids.new_full(beacon_size, fill_value=compression_ratio + mem_size)
829
+ position_ids[:, beacon_start_idx:] = beacon_position_ids
830
+
831
+ attention_mask[..., beacon_start_idx:, -window_size_with_beacon: -beacon_size] = ordinal_attention_mask
832
+ attention_mask[..., beacon_start_idx:, beacon_start_idx:] = beacon_attention_mask
833
+ # beacons of different ratios are blind to others
834
+ attention_mask[..., beacon_start_idx:, -beacon_size: beacon_start_idx] = min_value
835
+
836
+ elif self.config.beacon_pos == "interleave":
837
+ raise NotImplementedError
838
+
839
+ elif self.config.beacon_attn == "full-coverage":
840
+ pass
841
+
842
+ return attention_mask, position_ids
843
+
844
+ def _extract_beacon_and_raw_memory(
845
+ self,
846
+ key,
847
+ value,
848
+ previous_beacon_key,
849
+ previous_beacon_value,
850
+ previous_raw_key,
851
+ previous_raw_value,
852
+ beacon_indices,
853
+ ):
854
+ """Extract beacon and raw memory from the returned key and value when the window is full."""
855
+ key = cat_tensor([
856
+ previous_raw_key,
857
+ key
858
+ ], dim=self.k_seq_dim)
859
+ value = cat_tensor([
860
+ previous_raw_value,
861
+ value
862
+ ], dim=self.v_seq_dim)
863
+
864
+ # NOTE: we use magic slice instead of boolean index here for efficiency
865
+ beacon_key = slice_tensor(key, index=torch.logical_or(beacon_indices == 1, beacon_indices == -1), dim=self.k_seq_dim)
866
+ beacon_key = cat_tensor([previous_beacon_key, beacon_key], dim=self.k_seq_dim)
867
+ beacon_value = slice_tensor(value, index=torch.logical_or(beacon_indices == 1, beacon_indices == -1), dim=self.v_seq_dim)
868
+ beacon_value = cat_tensor([previous_beacon_value, beacon_value], dim=self.v_seq_dim)
869
+
870
+ if self._raw_size_to_cache > 0:
871
+ raw_key = slice_tensor(key, index=beacon_indices == 0, dim=self.k_seq_dim)
872
+ raw_key = slice_tensor(raw_key, start=-raw_size_to_cache, dim=self.k_seq_dim)
873
+
874
+ raw_value = slice_tensor(value, index=beacon_indices == 0, dim=self.v_seq_dim)
875
+ raw_value = slice_tensor(raw_value, start=-raw_size_to_cache, dim=self.v_seq_dim)
876
+
877
+ else:
878
+ raw_key = None
879
+ raw_value = None
880
+
881
+ return beacon_key, beacon_value, raw_key, raw_value
882
+
883
+
884
+ def slice_tensor(x, start=None, end=None, step=None, index=None, dim=2):
885
+ if x is None:
886
+ return None
887
+ if end == 0:
888
+ return None
889
+ if start == x.shape[dim]:
890
+ return None
891
+ if start is not None and start == end:
892
+ return None
893
+ if dim == 2:
894
+ if index is not None:
895
+ return x[:, :, index]
896
+ elif start is None and end is not None:
897
+ if step is None:
898
+ return x[:, :, :end, ...]
899
+ else:
900
+ return x[:, :, :end:step, ...]
901
+ elif start is not None and end is None:
902
+ if step is None:
903
+ return x[:, :, start:, ...]
904
+ else:
905
+ return x[:, :, start::step, ...]
906
+ elif start is not None and end is not None:
907
+ if step is None:
908
+ return x[:, :, start:end, ...]
909
+ else:
910
+ return x[:, :, start:end:step, ...]
911
+ elif dim == 1:
912
+ if index is not None:
913
+ return x[:, :, index]
914
+ elif start is None and end is not None:
915
+ if step is None:
916
+ return x[:, :end, ...]
917
+ else:
918
+ return x[:, :end:step, ...]
919
+ elif start is not None and end is None:
920
+ if step is None:
921
+ return x[:, start:, ...]
922
+ else:
923
+ return x[:, start::step, ...]
924
+ elif start is not None and end is not None:
925
+ if step is None:
926
+ return x[:, start:end, ...]
927
+ else:
928
+ return x[:, start:end:step, ...]
929
+ else:
930
+ raise NotImplementedError
931
+
932
+ def cat_tensor(list_of_tensors, dim=-1):
933
+ list_of_tensors = [t for t in list_of_tensors if t is not None]
934
+ if len(list_of_tensors) > 1:
935
+ result = torch.cat(list_of_tensors, dim=dim)
936
+ elif len(list_of_tensors) == 1:
937
+ result = list_of_tensors[0]
938
+ else:
939
+ result = None
940
+ return result
941
+
942
+ def slice_activations(activations, start=None, end=None, k_seq_dim=2, v_seq_dim=2):
943
+ new_activations = []
944
+ for key, value in activations:
945
+ new_key = slice_tensor(key, start=start, end=end, dim=k_seq_dim)
946
+ new_value = slice_tensor(value, start=start, end=end, dim=v_seq_dim)
947
+ new_activations.append([new_key, new_value])
948
+ return new_activations
949
+
950
+ def cat_activations(list_of_activations, k_seq_dim=2, v_seq_dim=2):
951
+ assert all(len(x) == len(list_of_activations[0]) for x in list_of_activations), f"Make sure all activations have the same number of layers! Found {[len(x) for x in list_of_activations]}."
952
+
953
+ new_activations = []
954
+ for layer_idx in range(len(list_of_activations[0])):
955
+ keys = [x[layer_idx][0] for x in list_of_activations]
956
+ values = [x[layer_idx][1] for x in list_of_activations]
957
+
958
+ new_key = cat_tensor(keys, dim=k_seq_dim)
959
+ new_value = cat_tensor(values, dim=v_seq_dim)
960
+ new_activations.append([new_key, new_value])
961
+ return new_activations
962
+
963
+ def interleave_activations(main_activations, augment_activations, main_spans, augment_spans, k_seq_dim=2, v_seq_dim=2, device=torch.device("cuda")):
964
+ """ Interleave main_activations and augment_activations according to main_span and augment_span.
965
+
966
+ Args:
967
+ main_span: a list of tuples (start_idx, end_idx). when start_idx and end_idx is None, the augment_activations will be plugged in.
968
+ augment_span: a list of tuples (start_idx, end_idx)
969
+ """
970
+ assert len(main_activations) == len(augment_activations) , f"Make sure main and augment activations have the same number of layers! Found {len(main_activations)} and {len(augment_activations)}!"
971
+ assert sum(x[0] is None and x[1] is None for x in main_spans) == len(augment_spans), f"Make sure the number of slots for augmentation (start_idx=None and end_idx=None in main_spans) matches the number of augmentations. Found {sum(x for x in main_spans if x[0] is None and x[1] is None)} slots but {len(augment_spans)} augmentations!"
972
+
973
+ new_activations = []
974
+ for layer_idx in range(len(main_activations)):
975
+ main_key, main_value = main_activations[layer_idx]
976
+ augment_key, augment_value = augment_activations[layer_idx]
977
+
978
+ sliced_keys = []
979
+ sliced_values = []
980
+
981
+ augment_idx = 0
982
+ for start, end in main_spans:
983
+ if start is None and end is None:
984
+ # this means the augment key/value should be plugged in
985
+ augment_start, augment_end = augment_spans[augment_idx]
986
+ sliced_key = slice_tensor(
987
+ augment_key,
988
+ start=augment_start,
989
+ end=augment_end,
990
+ dim=k_seq_dim
991
+ ).to(device)
992
+ sliced_value = slice_tensor(
993
+ augment_value,
994
+ start=augment_start,
995
+ end=augment_end,
996
+ dim=v_seq_dim
997
+ ).to(device)
998
+
999
+ else:
1000
+ sliced_key = slice_tensor(
1001
+ main_key,
1002
+ start=start,
1003
+ end=end,
1004
+ dim=k_seq_dim
1005
+ )
1006
+ sliced_value = slice_tensor(
1007
+ main_value,
1008
+ start=start,
1009
+ end=end,
1010
+ dim=v_seq_dim
1011
+ )
1012
+
1013
+ sliced_keys.append(sliced_key)
1014
+ sliced_values.append(sliced_value)
1015
+
1016
+ new_key = cat_tensor(sliced_keys, dim=k_seq_dim)
1017
+ new_value = cat_tensor(sliced_values, dim=v_seq_dim)
1018
+ new_activations.append([new_key, new_value])
1019
+
1020
+ return new_activations
1021
+
1022
+ def softmax(x:np.ndarray, axis=-1, temperature=1):
1023
+ if isinstance(x, list):
1024
+ x = np.array(x)
1025
+ x = x / temperature
1026
+ x = x - x.max(axis=axis, keepdims=True)
1027
+ y = np.exp(x)
1028
+ return y / y.sum(axis=axis, keepdims=True)
1029
+
1030
+ def l1_norm(x):
1031
+ sum_x = sum(x)
1032
+ x = [y/sum_x for y in x]
1033
+ return x
modeling_qwen2.py ADDED
@@ -0,0 +1,1619 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch Qwen2 model."""
21
+ import inspect
22
+ import math
23
+ import warnings
24
+ from typing import List, Optional, Tuple, Union
25
+
26
+ import torch
27
+ import torch.nn.functional as F
28
+ import torch.utils.checkpoint
29
+ from torch import nn
30
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
31
+
32
+ from transformers.activations import ACT2FN
33
+ from transformers.cache_utils import Cache, DynamicCache
34
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa
35
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
36
+ from transformers.modeling_utils import PreTrainedModel
37
+ from transformers.utils import (
38
+ add_start_docstrings,
39
+ add_start_docstrings_to_model_forward,
40
+ is_flash_attn_2_available,
41
+ is_flash_attn_greater_or_equal_2_10,
42
+ logging,
43
+ replace_return_docstrings,
44
+ )
45
+ from transformers.integrations import is_deepspeed_zero3_enabled
46
+
47
+
48
+ if is_flash_attn_2_available():
49
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
50
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
51
+
52
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
53
+
54
+ from .configuration_qwen2 import Qwen2Config
55
+ from .modeling_beacon import Memory
56
+ from .modeling_utils import optional_grad_ctx, compute_loss, BeaconModelOutput
57
+
58
+
59
+ logger = logging.get_logger(__name__)
60
+
61
+
62
+ _CHECKPOINT_FOR_DOC = "Qwen/Qwen2-7B-beta"
63
+ _CONFIG_FOR_DOC = "Qwen2Config"
64
+
65
+ QWEN2_PRETRAINED_MODEL_ARCHIVE_LIST = [
66
+ "Qwen/Qwen2-7B-beta",
67
+ # See all Qwen2 models at https://huggingface.co/models?filter=qwen2
68
+ ]
69
+
70
+
71
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
72
+ def _get_unpad_data(attention_mask):
73
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
74
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
75
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
76
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
77
+ return (
78
+ indices,
79
+ cu_seqlens,
80
+ max_seqlen_in_batch,
81
+ )
82
+
83
+
84
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Qwen2
85
+ class Qwen2RMSNorm(nn.Module):
86
+ def __init__(self, hidden_size, eps=1e-6):
87
+ """
88
+ Qwen2RMSNorm is equivalent to T5LayerNorm
89
+ """
90
+ super().__init__()
91
+ self.weight = nn.Parameter(torch.ones(hidden_size))
92
+ self.variance_epsilon = eps
93
+
94
+ def forward(self, hidden_states):
95
+ input_dtype = hidden_states.dtype
96
+ hidden_states = hidden_states.to(torch.float32)
97
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
98
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
99
+ return self.weight * hidden_states.to(input_dtype)
100
+
101
+
102
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
103
+ def rotate_half(x):
104
+ """Rotates half the hidden dims of the input."""
105
+ x1 = x[..., : x.shape[-1] // 2]
106
+ x2 = x[..., x.shape[-1] // 2 :]
107
+ return torch.cat((-x2, x1), dim=-1)
108
+
109
+
110
+ class Qwen2RotaryEmbedding(nn.Module):
111
+ def __init__(self, dim, max_position_embeddings=32768, base=10000, device=None):
112
+ super().__init__()
113
+
114
+ self.dim = dim
115
+ self.max_position_embeddings = max_position_embeddings
116
+ self.base = base
117
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
118
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
119
+
120
+ # Build here to make `torch.jit.trace` work.
121
+ self._set_cos_sin_cache(
122
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
123
+ )
124
+
125
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
126
+ self.max_seq_len_cached = seq_len
127
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
128
+
129
+ freqs = torch.outer(t, self.inv_freq)
130
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
131
+ emb = torch.cat((freqs, freqs), dim=-1)
132
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
133
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
134
+
135
+ def forward(self, q, k, position_ids):
136
+ seq_len = max(position_ids.max().item() + 1, k.shape[2])
137
+
138
+ # x: [bs, num_attention_heads, seq_len, head_size]
139
+ if seq_len > self.max_seq_len_cached:
140
+ self._set_cos_sin_cache(seq_len=seq_len, device=k.device, dtype=k.dtype)
141
+
142
+ # batch_size, 1, key_len, head_dim
143
+ k_cos = self.cos_cached[position_ids].to(dtype=k.dtype).unsqueeze(1)
144
+ k_sin = self.sin_cached[position_ids].to(dtype=k.dtype).unsqueeze(1)
145
+
146
+ q_cos = k_cos[..., -q.shape[2]:, :]
147
+ q_sin = k_sin[..., -q.shape[2]:, :]
148
+
149
+ q_embed = (q * q_cos) + (rotate_half(q) * q_sin)
150
+ k_embed = (k * k_cos) + (rotate_half(k) * k_sin)
151
+ return q_embed, k_embed
152
+
153
+
154
+ class Qwen2LinearScalingRotaryEmbedding(Qwen2RotaryEmbedding):
155
+ """Qwen2RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
156
+
157
+ def __init__(self, dim, max_position_embeddings=32768, base=10000, device=None, scaling_factor=1.0):
158
+ self.scaling_factor = scaling_factor
159
+ super().__init__(dim, max_position_embeddings, base, device)
160
+
161
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
162
+ self.max_seq_len_cached = seq_len
163
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
164
+ t = t / self.scaling_factor
165
+
166
+ freqs = torch.outer(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
+
173
+ class Qwen2DynamicNTKScalingRotaryEmbedding(Qwen2RotaryEmbedding):
174
+ """Qwen2RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
175
+
176
+ def __init__(self, dim, max_position_embeddings=32768, base=10000, device=None, scaling_factor=1.0):
177
+ self.scaling_factor = scaling_factor
178
+ super().__init__(dim, max_position_embeddings, base, device)
179
+
180
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
181
+ self.max_seq_len_cached = seq_len
182
+
183
+ if seq_len > self.max_position_embeddings:
184
+ base = self.base * (
185
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
186
+ ) ** (self.dim / (self.dim - 2))
187
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
188
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
189
+
190
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
191
+
192
+ freqs = torch.outer(t, self.inv_freq)
193
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
194
+ emb = torch.cat((freqs, freqs), dim=-1)
195
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
196
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
197
+
198
+
199
+ class Qwen2YarnRotaryEmbedding(nn.Module):
200
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0, beta_slow=2, beta_fast=128):
201
+ super().__init__()
202
+
203
+ self.base = base
204
+ self.dim = dim
205
+ self.scaling_factor = scaling_factor
206
+ self.beta_slow = beta_slow
207
+ self.beta_fast = beta_fast
208
+ self.max_position_embeddings = max_position_embeddings
209
+
210
+ self._set_cos_sin_cache(
211
+ seq_len=max_position_embeddings, device=device, dtype=torch.get_default_dtype()
212
+ )
213
+
214
+ def _get_factor(self, device, dtype):
215
+ # the dimension whose index is smaller than fast_dim rotates more than beta_fast
216
+ fast_dim = self.dim / 2 * (math.log(self.max_position_embeddings / (2 * math.pi * self.beta_fast)) / math.log(self.base))
217
+ fast_dim = max(math.floor(fast_dim), 0)
218
+ # the dimension whose index is bigger than slow_dim rotates less than beta_slow
219
+ slow_dim = self.dim / 2 * (math.log(self.max_position_embeddings / (2 * math.pi * self.beta_slow)) / math.log(self.base))
220
+ slow_dim = min(math.ceil(slow_dim), self.dim - 1)
221
+
222
+ if fast_dim == slow_dim:
223
+ slow_dim += 0.001
224
+
225
+ # NOTE: very important to use full precision here so that the factor is correct
226
+ dim_arange = torch.arange(0, self.dim // 2, device=device, dtype=torch.float32)
227
+ dim_factor = (dim_arange - fast_dim) / (slow_dim - fast_dim)
228
+ dim_factor = torch.clamp(dim_factor, 0, 1)
229
+
230
+ # align with the paper notation
231
+ return (1 - dim_factor)
232
+
233
+ def _get_temperature(self):
234
+ if self.scaling_factor <= 1:
235
+ return 1.0
236
+ return 0.07 * math.log(self.scaling_factor) + 1.0
237
+
238
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
239
+ dim_arange = torch.arange(0, self.dim, 2, device=device) / self.dim
240
+ # dim / 2
241
+ freq = self.base ** dim_arange
242
+ theta = 1 / freq
243
+ interleave_theta = theta / self.scaling_factor
244
+
245
+ factor = self._get_factor(device, dtype)
246
+ yarn_theta = factor * theta + (1 - factor) * interleave_theta
247
+ self.register_buffer("inv_freq", yarn_theta, persistent=False)
248
+
249
+ t = torch.arange(seq_len, device=device, dtype=self.inv_freq.dtype)
250
+ freqs = torch.outer(t, self.inv_freq)
251
+ emb = torch.cat((freqs, freqs), dim=-1)
252
+
253
+ # get attention temperature
254
+ temperature = self._get_temperature()
255
+
256
+ self.register_buffer("cos_cached", (emb.cos() * temperature).to(dtype), persistent=False)
257
+ self.register_buffer("sin_cached", (emb.sin() * temperature).to(dtype), persistent=False)
258
+ self.max_seq_len_cached = seq_len
259
+
260
+ def forward(self, q, k, position_ids):
261
+ seq_len = max(position_ids.max().item() + 1, k.shape[2])
262
+
263
+ # x: [bs, num_attention_heads, seq_len, head_size]
264
+ if seq_len > self.max_seq_len_cached:
265
+ self.scaling_factor = seq_len / self.max_position_embeddings
266
+ self._set_cos_sin_cache(seq_len=seq_len, device=k.device, dtype=k.dtype)
267
+
268
+ k_cos = self.cos_cached[position_ids].to(dtype=k.dtype).unsqueeze(1)
269
+ k_sin = self.sin_cached[position_ids].to(dtype=k.dtype).unsqueeze(1)
270
+
271
+ q_cos = k_cos[..., -q.shape[2]:, :]
272
+ q_sin = k_sin[..., -q.shape[2]:, :]
273
+
274
+ q_embed = (q * q_cos) + (rotate_half(q) * q_sin)
275
+ k_embed = (k * k_cos) + (rotate_half(k) * k_sin)
276
+ return q_embed, k_embed
277
+
278
+
279
+ # Copied from transformers.models.mistral.modeling_mistral.Qwen2MLP with Qwen2->Qwen2
280
+ class Qwen2MLP(nn.Module):
281
+ def __init__(self, config):
282
+ super().__init__()
283
+ self.config = config
284
+ self.hidden_size = config.hidden_size
285
+ self.intermediate_size = config.intermediate_size
286
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
287
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
288
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
289
+ self.act_fn = ACT2FN[config.hidden_act]
290
+
291
+ if "mlp" in config.beacon_param:
292
+ self.beacon_up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
293
+ self.beacon_up_proj.weight.data.zero_()
294
+ self.beacon_up_proj._is_hf_initialized = True
295
+
296
+ self.beacon_down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
297
+ self.beacon_down_proj.weight.data.zero_()
298
+ self.beacon_down_proj._is_hf_initialized = True
299
+
300
+ def _init_beacon_proj(self, missing_keys):
301
+ """Initialize the beacon projection weight with that of the ordinal projection."""
302
+ if "mlp" in self.config.beacon_param:
303
+ if is_deepspeed_zero3_enabled():
304
+ # FIXME: after deepspeed initialization, some weights becomes non-zero
305
+ # For Mistral, there are rows that are full of zeros
306
+ # For Mistral, there are values bigger than 1e29...
307
+
308
+ import deepspeed
309
+ params = [self.up_proj.weight, self.down_proj.weight, self.beacon_up_proj.weight, self.beacon_down_proj.weight]
310
+ with deepspeed.zero.GatheredParameters(params, modifier_rank=0):
311
+ if (self.beacon_up_proj.weight.sum(-1) == 0).any() or (self.beacon_up_proj.weight > 1e29).any():
312
+ self.beacon_up_proj.weight.data[:] = self.up_proj.weight.data
313
+ self.beacon_down_proj.weight.data[:] = self.down_proj.weight.data
314
+ else:
315
+ if any("beacon_up_proj" in missing_key for missing_key in missing_keys):
316
+ # only copy the value in-place, without tieing the weight
317
+ self.beacon_up_proj.weight.data[:] = self.up_proj.weight.data
318
+ self.beacon_down_proj.weight.data[:] = self.down_proj.weight.data
319
+
320
+ def forward(self, x, beacon_size, beacon_indices):
321
+ if "mlp" in self.config.beacon_param:
322
+ # NOTE: when beacon_pos == "interleave", the beacon_indices points to all beacon tokens in the current window (cached activations + input_ids), so we shall slice out the part corresponding to the input_ids
323
+ if beacon_size > 0:
324
+ cur_beacon_indices = beacon_indices[-x.shape[1]:]
325
+ ordinal_hidden_states = x[:, cur_beacon_indices == 0]
326
+ beacon_hidden_states = x[:, cur_beacon_indices == 1]
327
+
328
+ ordinal_down_proj = self.down_proj(self.act_fn(self.gate_proj(ordinal_hidden_states)) * self.up_proj(ordinal_hidden_states))
329
+ beacon_down_proj = self.beacon_down_proj(self.act_fn(self.gate_proj(beacon_hidden_states)) * self.beacon_up_proj(beacon_hidden_states))
330
+
331
+ down_proj = beacon_down_proj.new_ones(x.shape)
332
+ down_proj[:, beacon_indices == 0] = ordinal_down_proj
333
+ down_proj[:, beacon_indices == 1] = beacon_down_proj
334
+ else:
335
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
336
+ else:
337
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
338
+
339
+ return down_proj
340
+
341
+
342
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
343
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
344
+ """
345
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
346
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
347
+ """
348
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
349
+ if n_rep == 1:
350
+ return hidden_states
351
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
352
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
353
+
354
+
355
+ class Qwen2Attention(nn.Module):
356
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
357
+
358
+ def __init__(self, config: Qwen2Config, layer_idx: Optional[int] = None):
359
+ super().__init__()
360
+ self.config = config
361
+ self.layer_idx = layer_idx
362
+ if layer_idx is None:
363
+ logger.warning_once(
364
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
365
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
366
+ "when creating this class."
367
+ )
368
+
369
+ self.attention_dropout = config.attention_dropout
370
+ self.hidden_size = config.hidden_size
371
+ self.num_heads = config.num_attention_heads
372
+ self.head_dim = self.hidden_size // self.num_heads
373
+ self.num_key_value_heads = config.num_key_value_heads
374
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
375
+ self.max_position_embeddings = config.max_position_embeddings
376
+ self.rope_theta = config.rope_theta
377
+ self.is_causal = True
378
+
379
+ if (self.head_dim * self.num_heads) != self.hidden_size:
380
+ raise ValueError(
381
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
382
+ f" and `num_heads`: {self.num_heads})."
383
+ )
384
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
385
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
386
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
387
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
388
+
389
+ self._init_rope()
390
+
391
+ # NOTE: add extra parameters for beacon tokens
392
+ # skip post initialization to speed up loading
393
+ if "q" in config.beacon_param:
394
+ self.beacon_q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=self.q_proj.bias is not None)
395
+ # NOTE: initialize the beacon parameters as zero
396
+ self.beacon_q_proj.weight.data.zero_()
397
+ self.beacon_q_proj._is_hf_initialized = True
398
+ if "k" in config.beacon_param:
399
+ self.beacon_k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=self.k_proj.bias is not None)
400
+ self.beacon_k_proj.weight.data.zero_()
401
+ self.beacon_k_proj._is_hf_initialized = True
402
+ if "v" in config.beacon_param:
403
+ self.beacon_v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=self.v_proj.bias is not None)
404
+ self.beacon_v_proj.weight.data.zero_()
405
+ self.beacon_v_proj._is_hf_initialized = True
406
+ if "o" in config.beacon_param:
407
+ self.beacon_o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=self.o_proj.bias is not None)
408
+ self.beacon_o_proj.weight.data.zero_()
409
+ self.beacon_o_proj._is_hf_initialized = True
410
+
411
+ def _init_rope(self):
412
+ if self.config.rope_scaling is None:
413
+ self.rotary_emb = Qwen2RotaryEmbedding(
414
+ self.head_dim,
415
+ max_position_embeddings=self.max_position_embeddings,
416
+ base=self.rope_theta,
417
+ )
418
+ else:
419
+ scaling_type = self.config.rope_scaling["type"]
420
+ scaling_factor = self.config.rope_scaling["factor"]
421
+ if scaling_type == "linear":
422
+ self.rotary_emb = Qwen2LinearScalingRotaryEmbedding(
423
+ self.head_dim,
424
+ max_position_embeddings=self.max_position_embeddings,
425
+ scaling_factor=scaling_factor,
426
+ base=self.rope_theta,
427
+ )
428
+ elif scaling_type == "dynamic":
429
+ self.rotary_emb = Qwen2DynamicNTKScalingRotaryEmbedding(
430
+ self.head_dim,
431
+ max_position_embeddings=self.max_position_embeddings,
432
+ scaling_factor=scaling_factor,
433
+ base=self.rope_theta,
434
+ )
435
+ elif scaling_type == "yarn":
436
+ self.rotary_emb = Qwen2YarnRotaryEmbedding(
437
+ self.head_dim,
438
+ max_position_embeddings=self.max_position_embeddings,
439
+ scaling_factor=scaling_factor,
440
+ base=self.rope_theta,
441
+ )
442
+ elif scaling_type == "yarn-t":
443
+ self.rotary_emb = Qwen2YarnDynamicTemperatureRotaryEmbedding(
444
+ self.head_dim,
445
+ max_position_embeddings=self.max_position_embeddings,
446
+ scaling_factor=scaling_factor,
447
+ base=self.rope_theta,
448
+ )
449
+ elif scaling_type == "yarn-t-logn":
450
+ self.rotary_emb = Qwen2YarnDynamicTemperatureLogNRotaryEmbedding(
451
+ self.head_dim,
452
+ max_position_embeddings=self.max_position_embeddings,
453
+ scaling_factor=scaling_factor,
454
+ base=self.rope_theta,
455
+ )
456
+ else:
457
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
458
+
459
+ def _init_beacon_proj(self, missing_keys):
460
+ """Initialize the beacon projection weight with that of the ordinal projection."""
461
+ beacon_param = self.config.beacon_param
462
+
463
+ if is_deepspeed_zero3_enabled():
464
+ # FIXME: after deepspeed initialization, some weights becomes non-zero
465
+ # For Mistral, there are rows that are full of zeros
466
+ # For Mistral, there are values bigger than 1e29...
467
+
468
+ import deepspeed
469
+ if "q" in beacon_param:
470
+ params = [self.beacon_q_proj.weight, self.q_proj.weight]
471
+ if self.q_proj.bias is not None:
472
+ params.extend([self.beacon_q_proj.bias, self.q_proj.bias])
473
+ with deepspeed.zero.GatheredParameters(params, modifier_rank=0):
474
+ # FIXME: after deepspeed initialization, some weights becomes non-zero, but there are rows that are full of zeros
475
+ if (self.beacon_q_proj.weight.sum(-1) == 0).any() or (self.beacon_q_proj.weight > 1e29).any():
476
+ self.beacon_q_proj.weight.data[:] = self.q_proj.weight.data
477
+ if self.q_proj.bias is not None:
478
+ self.beacon_q_proj.bias.data[:] = self.q_proj.bias.data
479
+ if "k" in beacon_param:
480
+ params = [self.beacon_k_proj.weight, self.k_proj.weight]
481
+ if self.k_proj.bias is not None:
482
+ params.extend([self.beacon_k_proj.bias, self.k_proj.bias])
483
+ with deepspeed.zero.GatheredParameters(params, modifier_rank=0):
484
+ # FIXME: after deepspeed initialization, some weights becomes non-zero, but there are rows that are full of zeros
485
+ if (self.beacon_k_proj.weight.sum(-1) == 0).any() or (self.beacon_k_proj.weight > 1e29).any():
486
+ self.beacon_k_proj.weight.data[:] = self.k_proj.weight.data
487
+ if self.k_proj.bias is not None:
488
+ self.beacon_k_proj.bias.data[:] = self.k_proj.bias.data
489
+ if "v" in beacon_param:
490
+ params = [self.beacon_v_proj.weight, self.v_proj.weight]
491
+ if self.v_proj.bias is not None:
492
+ params.extend([self.beacon_v_proj.bias, self.v_proj.bias])
493
+ with deepspeed.zero.GatheredParameters(params, modifier_rank=0):
494
+ # FIXME: after deepspeed initialization, some weights becomes non-zero, but there are rows that are full of zeros
495
+ if (self.beacon_v_proj.weight.sum(-1) == 0).any() or (self.beacon_v_proj.weight > 1e29).any():
496
+ self.beacon_v_proj.weight.data[:] = self.v_proj.weight.data
497
+ if self.v_proj.bias is not None:
498
+ self.beacon_v_proj.bias.data[:] = self.v_proj.bias.data
499
+ if "o" in beacon_param:
500
+ params = [self.beacon_o_proj.weight, self.o_proj.weight]
501
+ if self.o_proj.bias is not None:
502
+ params.extend([self.beacon_o_proj.bias, self.o_proj.bias])
503
+ with deepspeed.zero.GatheredParameters(params, modifier_rank=0):
504
+ # FIXME: after deepspeed initialization, some weights becomes non-zero, but there are rows that are full of zeros
505
+ if (self.beacon_o_proj.weight.sum(-1) == 0).any() or (self.beacon_o_proj.weight > 1e29).any():
506
+ self.beacon_o_proj.weight.data[:] = self.o_proj.weight.data
507
+ if self.o_proj.bias is not None:
508
+ self.beacon_o_proj.bias.data[:] = self.o_proj.bias.data
509
+ else:
510
+ # only copy the value in-place, without tieing the weight
511
+ if "q" in beacon_param and any("beacon_q_proj" in missing_key for missing_key in missing_keys):
512
+ # FIXME: some beacon weights are not initialized as zero for mistral model, why?
513
+ # if (self.beacon_q_proj.weight == 0).all():
514
+ self.beacon_q_proj.weight.data[:] = self.q_proj.weight.data
515
+ if self.q_proj.bias is not None:
516
+ self.beacon_q_proj.bias.data[:] = self.q_proj.bias.data
517
+ if "k" in beacon_param and any("beacon_k_proj" in missing_key for missing_key in missing_keys):
518
+ # if (self.beacon_k_proj.weight == 0).all():
519
+ self.beacon_k_proj.weight.data[:] = self.k_proj.weight.data
520
+ if self.k_proj.bias is not None:
521
+ self.beacon_k_proj.bias.data[:] = self.k_proj.bias.data
522
+ if "v" in beacon_param and any("beacon_v_proj" in missing_key for missing_key in missing_keys):
523
+ # if (self.beacon_v_proj.weight == 0).all():
524
+ self.beacon_v_proj.weight.data[:] = self.v_proj.weight.data
525
+ if self.v_proj.bias is not None:
526
+ self.beacon_v_proj.bias.data[:] = self.v_proj.bias.data
527
+ if "o" in beacon_param and any("beacon_o_proj" in missing_key for missing_key in missing_keys):
528
+ # if (self.beacon_o_proj.weight == 0).all():
529
+ self.beacon_o_proj.weight.data[:] = self.o_proj.weight.data
530
+ if self.o_proj.bias is not None:
531
+ self.beacon_o_proj.bias.data[:] = self.o_proj.bias.data
532
+
533
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
534
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
535
+
536
+ def qkv_proj_with_beacon(self, hidden_states, beacon_size, beacon_indices):
537
+ if beacon_size > 0:
538
+ # NOTE: when beacon_pos == "interleave", the beacon_indices points to all beacon tokens in the current window (cached activations + input_ids), so we shall slice out the part corresponding to the input_ids
539
+ cur_beacon_indices = beacon_indices[-hidden_states.shape[1]:]
540
+
541
+ ordinal_hidden_states = hidden_states[:, cur_beacon_indices == 0]
542
+ beacon_hidden_states = hidden_states[:, cur_beacon_indices == 1]
543
+
544
+ if "q" in self.config.beacon_param:
545
+ ordinal_query_states = self.q_proj(ordinal_hidden_states)
546
+ beacon_query_states = self.beacon_q_proj(beacon_hidden_states)
547
+ query_states = beacon_query_states.new_zeros((ordinal_query_states.shape[0], cur_beacon_indices.shape[0], ordinal_query_states.shape[2]))
548
+ query_states[:, cur_beacon_indices == 0] = ordinal_query_states
549
+ query_states[:, cur_beacon_indices == 1] = beacon_query_states
550
+ # NOTE: replicate hidden states for beacon tokens in case of parallel windows
551
+ if (cur_beacon_indices == 2).any():
552
+ query_states[:, cur_beacon_indices == 2] = beacon_query_states[:, :(cur_beacon_indices == 2).sum()]
553
+
554
+ else:
555
+ query_states = self.q_proj(hidden_states)
556
+
557
+ if "k" in self.config.beacon_param:
558
+ ordinal_key_states = self.k_proj(ordinal_hidden_states)
559
+ beacon_key_states = self.beacon_k_proj(beacon_hidden_states)
560
+ key_states = beacon_key_states.new_zeros((ordinal_key_states.shape[0], cur_beacon_indices.shape[0], ordinal_key_states.shape[2]))
561
+ key_states[:, cur_beacon_indices == 0] = ordinal_key_states
562
+ key_states[:, cur_beacon_indices == 1] = beacon_key_states
563
+ # NOTE: replicate hidden states for beacon tokens in case of parallel windows
564
+ if (cur_beacon_indices == 2).any():
565
+ key_states[:, cur_beacon_indices == 2] = beacon_key_states[:, :(cur_beacon_indices == 2).sum()]
566
+
567
+ else:
568
+ key_states = self.k_proj(hidden_states)
569
+
570
+ if "v" in self.config.beacon_param:
571
+ ordinal_value_states = self.v_proj(ordinal_hidden_states)
572
+ beacon_value_states = self.beacon_v_proj(beacon_hidden_states)
573
+ value_states = beacon_value_states.new_zeros((ordinal_value_states.shape[0], cur_beacon_indices.shape[0], ordinal_value_states.shape[2]))
574
+ value_states[:, cur_beacon_indices == 0] = ordinal_value_states
575
+ value_states[:, cur_beacon_indices == 1] = beacon_value_states
576
+ # NOTE: replicate hidden states for beacon tokens in case of parallel windows
577
+ if (cur_beacon_indices == 2).any():
578
+ value_states[:, cur_beacon_indices == 2] = beacon_value_states[:, :(cur_beacon_indices == 2).sum()]
579
+ else:
580
+ value_states = self.v_proj(hidden_states)
581
+
582
+ else:
583
+ query_states = self.q_proj(hidden_states)
584
+ key_states = self.k_proj(hidden_states)
585
+ value_states = self.v_proj(hidden_states)
586
+
587
+ return query_states, key_states, value_states
588
+
589
+ def o_proj_with_beacon(self, attn_output, beacon_size, beacon_indices):
590
+ if beacon_size > 0:
591
+ # NOTE: when beacon_pos == "interleave", the beacon_indices points to all beacon tokens in the current window (cached activations + input_ids), so we shall slice out the part corresponding to the input_ids
592
+ cur_beacon_indices = beacon_indices[-attn_output.shape[1]:]
593
+
594
+ if "o" in self.config.beacon_param:
595
+ ordinal_attn_output = self.o_proj(attn_output[:, cur_beacon_indices == 0])
596
+ beacon_attn_output = self.beacon_o_proj(attn_output[:, cur_beacon_indices == 1])
597
+ attn_output = beacon_attn_output.new_zeros(attn_output.shape)
598
+ attn_output[:, cur_beacon_indices == 0] = ordinal_attn_output
599
+ attn_output[:, cur_beacon_indices == 1] = beacon_attn_output
600
+ # NOTE: replicate hidden states for beacon tokens in case of parallel windows
601
+ # if (cur_beacon_indices == 2).any():
602
+ # attn_output[:, cur_beacon_indices == 2] = beacon_attn_output[:, :(cur_beacon_indices == 2).sum()]
603
+ else:
604
+ attn_output = self.o_proj(attn_output)
605
+ else:
606
+ attn_output = self.o_proj(attn_output)
607
+ return attn_output
608
+
609
+ def forward(
610
+ self,
611
+ hidden_states: torch.Tensor,
612
+ attention_mask: Optional[torch.Tensor] = None,
613
+ position_ids: Optional[torch.LongTensor] = None,
614
+ past_key_value: Optional[Cache] = None,
615
+ output_attentions: bool = False,
616
+ use_cache: bool = False,
617
+ **kwargs,
618
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
619
+ if "padding_mask" in kwargs:
620
+ warnings.warn(
621
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
622
+ )
623
+
624
+ bsz, q_len, _ = hidden_states.size()
625
+ kv_seq_len = hidden_states.shape[-2]
626
+ past_key, past_value, beacon_size, beacon_indices = past_key_value
627
+
628
+ if past_key is not None:
629
+ past_seq_len = past_key.shape[2]
630
+ kv_seq_len += past_seq_len
631
+ else:
632
+ past_seq_len = 0
633
+
634
+ query_states, key_states, value_states = self.qkv_proj_with_beacon(hidden_states, beacon_size, beacon_indices)
635
+
636
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
637
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
638
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
639
+
640
+ # return keys and values before rope
641
+ # NOTE: incrementally return keys and values for efficiency
642
+ past_key_value = (key_states, value_states, beacon_size, beacon_indices)
643
+
644
+ if past_key is not None:
645
+ # reuse k, v, self_attention
646
+ key_states = torch.cat([past_key, key_states], dim=2)
647
+ value_states = torch.cat([past_value, value_states], dim=2)
648
+
649
+ query_states, key_states = self.rotary_emb(query_states, key_states, position_ids)
650
+
651
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
652
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
653
+
654
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
655
+
656
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
657
+ raise ValueError(
658
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
659
+ f" {attn_weights.size()}"
660
+ )
661
+
662
+ if attention_mask is not None:
663
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
664
+ raise ValueError(
665
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
666
+ )
667
+ attn_weights = attn_weights + attention_mask
668
+
669
+ # upcast attention to fp32
670
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
671
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
672
+ attn_output = torch.matmul(attn_weights, value_states)
673
+
674
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
675
+ raise ValueError(
676
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
677
+ f" {attn_output.size()}"
678
+ )
679
+
680
+ attn_output = attn_output.transpose(1, 2).contiguous()
681
+
682
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
683
+
684
+ attn_output = self.o_proj_with_beacon(attn_output, beacon_size, beacon_indices)
685
+
686
+ if not output_attentions:
687
+ attn_weights = None
688
+
689
+ return attn_output, attn_weights, past_key_value
690
+
691
+
692
+ class Qwen2SdpaAttention(Qwen2Attention):
693
+ """
694
+ Qwen2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
695
+ `Qwen2Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
696
+ SDPA API.
697
+ """
698
+
699
+ # Adapted from Qwen2Attention.forward
700
+ def forward(
701
+ self,
702
+ hidden_states: torch.Tensor,
703
+ attention_mask: Optional[torch.Tensor] = None,
704
+ position_ids: Optional[torch.LongTensor] = None,
705
+ past_key_value: Optional[Cache] = None,
706
+ output_attentions: bool = False,
707
+ use_cache: bool = False,
708
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
709
+ if output_attentions:
710
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
711
+ logger.warning_once(
712
+ "Qwen2Model is using Qwen2SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
713
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
714
+ )
715
+ return super().forward(
716
+ hidden_states=hidden_states,
717
+ attention_mask=attention_mask,
718
+ position_ids=position_ids,
719
+ past_key_value=past_key_value,
720
+ output_attentions=output_attentions,
721
+ use_cache=use_cache,
722
+ )
723
+ bsz, q_len, _ = hidden_states.size()
724
+ kv_seq_len = hidden_states.shape[-2]
725
+ past_key, past_value, beacon_size, beacon_indices = past_key_value
726
+ if past_key is not None:
727
+ past_seq_len = past_key.shape[2]
728
+ kv_seq_len += past_seq_len
729
+ else:
730
+ past_seq_len = 0
731
+
732
+ query_states, key_states, value_states = self.qkv_proj_with_beacon(hidden_states, beacon_size, beacon_indices)
733
+
734
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
735
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
736
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
737
+
738
+ # return keys and values before rope
739
+ # NOTE: incrementally return keys and values for efficiency
740
+ past_key_value = (key_states, value_states, beacon_size, beacon_indices)
741
+
742
+ if past_key is not None:
743
+ # reuse k, v, self_attention
744
+ key_states = torch.cat([past_key, key_states], dim=2)
745
+ value_states = torch.cat([past_value, value_states], dim=2)
746
+
747
+ query_states, key_states = self.rotary_emb(query_states, key_states, position_ids)
748
+
749
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
750
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
751
+
752
+ if attention_mask is not None:
753
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
754
+ raise ValueError(
755
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
756
+ )
757
+
758
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
759
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
760
+ if query_states.device.type == "cuda" and attention_mask is not None:
761
+ query_states = query_states.contiguous()
762
+ key_states = key_states.contiguous()
763
+ value_states = value_states.contiguous()
764
+
765
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
766
+ query_states,
767
+ key_states,
768
+ value_states,
769
+ attn_mask=attention_mask,
770
+ dropout_p=self.attention_dropout if self.training else 0.0,
771
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
772
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
773
+ )
774
+
775
+ attn_output = attn_output.transpose(1, 2).contiguous()
776
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
777
+ attn_output = self.o_proj_with_beacon(attn_output, beacon_size, beacon_indices)
778
+
779
+ return attn_output, None, past_key_value
780
+
781
+
782
+ class Qwen2FlashAttention2(Qwen2Attention):
783
+ """
784
+ Qwen2 flash attention module. This module inherits from `Qwen2Attention` as the weights of the module stays
785
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
786
+ flash attention and deal with padding tokens in case the input contains any of them.
787
+ """
788
+
789
+ def __init__(self, *args, **kwargs):
790
+ super().__init__(*args, **kwargs)
791
+
792
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
793
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
794
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
795
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
796
+
797
+ def forward(
798
+ self,
799
+ hidden_states: torch.Tensor,
800
+ attention_mask: Optional[torch.LongTensor] = None,
801
+ position_ids: Optional[torch.LongTensor] = None,
802
+ past_key_value: Optional[Cache] = None,
803
+ output_attentions: bool = False,
804
+ use_cache: bool = False,
805
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
806
+ output_attentions = False
807
+
808
+ bsz, q_len, _ = hidden_states.size()
809
+ kv_seq_len = hidden_states.shape[-2]
810
+
811
+ past_key, past_value, beacon_size, beacon_indices = past_key_value
812
+ if past_key is not None:
813
+ past_seq_len = past_key.shape[2]
814
+ kv_seq_len += past_seq_len
815
+ else:
816
+ past_seq_len = 0
817
+
818
+ query_states, key_states, value_states = self.qkv_proj_with_beacon(hidden_states, beacon_size, beacon_indices)
819
+
820
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
821
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
822
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
823
+
824
+ # return keys and values before rope
825
+ # NOTE: incrementally return keys and values for efficiency
826
+ past_key_value = (key_states, value_states, beacon_size, beacon_indices)
827
+
828
+ if past_key is not None:
829
+ # reuse k, v, self_attention
830
+ key_states = torch.cat([past_key, key_states], dim=2)
831
+ value_states = torch.cat([past_value, value_states], dim=2)
832
+
833
+ query_states, key_states = self.rotary_emb(query_states, key_states, position_ids)
834
+
835
+ # FlashAttention will automatically handle grouped query attention
836
+ # key_states = repeat_kv(key_states, self.num_key_value_groups)
837
+ # value_states = repeat_kv(value_states, self.num_key_value_groups)
838
+
839
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
840
+ # to be able to avoid many of these transpose/reshape/view.
841
+ query_states = query_states.transpose(1, 2)
842
+ key_states = key_states.transpose(1, 2)
843
+ value_states = value_states.transpose(1, 2)
844
+
845
+ dropout_rate = self.attention_dropout if self.training else 0.0
846
+
847
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
848
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
849
+ # cast them back in the correct dtype just to be sure everything works as expected.
850
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
851
+ # in fp32. (Qwen2RMSNorm handles it correctly)
852
+
853
+ input_dtype = query_states.dtype
854
+ if input_dtype == torch.float32:
855
+ if torch.is_autocast_enabled():
856
+ target_dtype = torch.get_autocast_gpu_dtype()
857
+ # Handle the case where the model is quantized
858
+ elif hasattr(self.config, "_pre_quantization_dtype"):
859
+ target_dtype = self.config._pre_quantization_dtype
860
+ else:
861
+ target_dtype = self.q_proj.weight.dtype
862
+
863
+ logger.warning_once(
864
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
865
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
866
+ f" {target_dtype}."
867
+ )
868
+
869
+ query_states = query_states.to(target_dtype)
870
+ key_states = key_states.to(target_dtype)
871
+ value_states = value_states.to(target_dtype)
872
+
873
+ attn_output = self._flash_attention_forward(
874
+ query_states,
875
+ key_states,
876
+ value_states,
877
+ attention_mask,
878
+ q_len,
879
+ dropout=dropout_rate
880
+ )
881
+
882
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
883
+ attn_output = self.o_proj_with_beacon(attn_output, beacon_size, beacon_indices)
884
+
885
+ if not output_attentions:
886
+ attn_weights = None
887
+
888
+ return attn_output, attn_weights, past_key_value
889
+
890
+ def _flash_attention_forward(
891
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
892
+ ):
893
+ """
894
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
895
+ first unpad the input, then computes the attention scores and pad the final attention scores.
896
+
897
+ Args:
898
+ query_states (`torch.Tensor`):
899
+ Input query states to be passed to Flash Attention API
900
+ key_states (`torch.Tensor`):
901
+ Input key states to be passed to Flash Attention API
902
+ value_states (`torch.Tensor`):
903
+ Input value states to be passed to Flash Attention API
904
+ attention_mask (`torch.Tensor`):
905
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
906
+ position of padding tokens and 1 for the position of non-padding tokens.
907
+ dropout (`float`):
908
+ Attention dropout
909
+ softmax_scale (`float`, *optional*):
910
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
911
+ """
912
+ if not self._flash_attn_uses_top_left_mask:
913
+ causal = self.is_causal
914
+ else:
915
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in Qwen2FlashAttention2 __init__.
916
+ causal = self.is_causal and query_length != 1
917
+
918
+ # Contains at least one padding token in the sequence
919
+ if attention_mask is not None:
920
+ batch_size = query_states.shape[0]
921
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
922
+ query_states, key_states, value_states, attention_mask, query_length
923
+ )
924
+
925
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
926
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
927
+
928
+ attn_output_unpad = flash_attn_varlen_func(
929
+ query_states,
930
+ key_states,
931
+ value_states,
932
+ cu_seqlens_q=cu_seqlens_q,
933
+ cu_seqlens_k=cu_seqlens_k,
934
+ max_seqlen_q=max_seqlen_in_batch_q,
935
+ max_seqlen_k=max_seqlen_in_batch_k,
936
+ dropout_p=dropout,
937
+ softmax_scale=softmax_scale,
938
+ causal=causal,
939
+ )
940
+
941
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
942
+ else:
943
+ attn_output = flash_attn_func(
944
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
945
+ )
946
+
947
+ return attn_output
948
+
949
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
950
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
951
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
952
+
953
+ key_layer = index_first_axis(
954
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
955
+ )
956
+ value_layer = index_first_axis(
957
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
958
+ )
959
+ if query_length == kv_seq_len:
960
+ query_layer = index_first_axis(
961
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
962
+ )
963
+ cu_seqlens_q = cu_seqlens_k
964
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
965
+ indices_q = indices_k
966
+ elif query_length == 1:
967
+ max_seqlen_in_batch_q = 1
968
+ cu_seqlens_q = torch.arange(
969
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
970
+ ) # There is a memcpy here, that is very bad.
971
+ indices_q = cu_seqlens_q[:-1]
972
+ query_layer = query_layer.squeeze(1)
973
+ else:
974
+ # The -q_len: slice assumes left padding.
975
+ attention_mask = attention_mask[:, -query_length:]
976
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
977
+
978
+ return (
979
+ query_layer,
980
+ key_layer,
981
+ value_layer,
982
+ indices_q,
983
+ (cu_seqlens_q, cu_seqlens_k),
984
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
985
+ )
986
+
987
+
988
+ QWEN2_ATTENTION_CLASSES = {
989
+ "eager": Qwen2Attention,
990
+ "sdpa": Qwen2SdpaAttention,
991
+ "flash_attention_2": Qwen2FlashAttention2,
992
+ }
993
+
994
+
995
+ class Qwen2DecoderLayer(nn.Module):
996
+ def __init__(self, config: Qwen2Config, layer_idx: int):
997
+ super().__init__()
998
+ self.hidden_size = config.hidden_size
999
+
1000
+ if config.use_sliding_window and config._attn_implementation != "flash_attention_2":
1001
+ logger.warning_once(
1002
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
1003
+ "unexpected results may be encountered."
1004
+ )
1005
+ self.self_attn = QWEN2_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
1006
+
1007
+ self.mlp = Qwen2MLP(config)
1008
+ self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1009
+ self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1010
+
1011
+ def forward(
1012
+ self,
1013
+ hidden_states: torch.Tensor,
1014
+ attention_mask: Optional[torch.Tensor] = None,
1015
+ position_ids: Optional[torch.LongTensor] = None,
1016
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1017
+ output_attentions: Optional[bool] = False,
1018
+ use_cache: Optional[bool] = False,
1019
+ **kwargs,
1020
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
1021
+ if "padding_mask" in kwargs:
1022
+ warnings.warn(
1023
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
1024
+ "Please make sure use `attention_mask` instead.`"
1025
+ )
1026
+ """
1027
+ Args:
1028
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1029
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
1030
+ `(batch, sequence_length)` where padding elements are indicated by 0.
1031
+ output_attentions (`bool`, *optional*):
1032
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1033
+ returned tensors for more detail.
1034
+ use_cache (`bool`, *optional*):
1035
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1036
+ (see `past_key_values`).
1037
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1038
+ """
1039
+
1040
+ # NOTE: get beacon_size in case the mlp is included in beacon_param
1041
+ past_key, past_value, beacon_size, beacon_indices = past_key_value
1042
+
1043
+ residual = hidden_states
1044
+
1045
+ hidden_states = self.input_layernorm(hidden_states)
1046
+
1047
+ # Self Attention
1048
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1049
+ hidden_states=hidden_states,
1050
+ attention_mask=attention_mask,
1051
+ position_ids=position_ids,
1052
+ past_key_value=past_key_value,
1053
+ output_attentions=output_attentions,
1054
+ use_cache=use_cache,
1055
+ )
1056
+ hidden_states = residual + hidden_states
1057
+
1058
+ # Fully Connected
1059
+ residual = hidden_states
1060
+ hidden_states = self.post_attention_layernorm(hidden_states)
1061
+ hidden_states = self.mlp(hidden_states, beacon_size, beacon_indices)
1062
+ hidden_states = residual + hidden_states
1063
+
1064
+ outputs = (hidden_states,)
1065
+
1066
+ if output_attentions:
1067
+ outputs += (self_attn_weights,)
1068
+
1069
+ if use_cache:
1070
+ outputs += (present_key_value,)
1071
+
1072
+ return outputs
1073
+
1074
+
1075
+ QWEN2_START_DOCSTRING = r"""
1076
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1077
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1078
+ etc.)
1079
+
1080
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1081
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1082
+ and behavior.
1083
+
1084
+ Parameters:
1085
+ config ([`Qwen2Config`]):
1086
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1087
+ load the weights associated with the model, only the configuration. Check out the
1088
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1089
+ """
1090
+
1091
+
1092
+ @add_start_docstrings(
1093
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
1094
+ QWEN2_START_DOCSTRING,
1095
+ )
1096
+ class Qwen2PreTrainedModel(PreTrainedModel):
1097
+ config_class = Qwen2Config
1098
+ base_model_prefix = "model"
1099
+ supports_gradient_checkpointing = True
1100
+ _no_split_modules = ["Qwen2DecoderLayer"]
1101
+ _skip_keys_device_placement = "past_key_values"
1102
+ _supports_flash_attn_2 = True
1103
+ _supports_sdpa = True
1104
+ _supports_cache_class = True
1105
+
1106
+ def _init_weights(self, module):
1107
+ std = self.config.initializer_range
1108
+ if isinstance(module, nn.Linear):
1109
+ module.weight.data.normal_(mean=0.0, std=std)
1110
+ if module.bias is not None:
1111
+ module.bias.data.zero_()
1112
+ elif isinstance(module, nn.Embedding):
1113
+ module.weight.data.normal_(mean=0.0, std=std)
1114
+ if module.padding_idx is not None:
1115
+ module.weight.data[module.padding_idx].zero_()
1116
+
1117
+
1118
+ QWEN2_INPUTS_DOCSTRING = r"""
1119
+ Args:
1120
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1121
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1122
+ it.
1123
+
1124
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1125
+ [`PreTrainedTokenizer.__call__`] for details.
1126
+
1127
+ [What are input IDs?](../glossary#input-ids)
1128
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1129
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1130
+
1131
+ - 1 for tokens that are **not masked**,
1132
+ - 0 for tokens that are **masked**.
1133
+
1134
+ [What are attention masks?](../glossary#attention-mask)
1135
+
1136
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1137
+ [`PreTrainedTokenizer.__call__`] for details.
1138
+
1139
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
1140
+ `past_key_values`).
1141
+
1142
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1143
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1144
+ information on the default strategy.
1145
+
1146
+ - 1 indicates the head is **not masked**,
1147
+ - 0 indicates the head is **masked**.
1148
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1149
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1150
+ config.n_positions - 1]`.
1151
+
1152
+ [What are position IDs?](../glossary#position-ids)
1153
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1154
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1155
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1156
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1157
+
1158
+ Two formats are allowed:
1159
+ - a [`~cache_utils.Cache`] instance;
1160
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1161
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1162
+ cache format.
1163
+
1164
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1165
+ legacy cache format will be returned.
1166
+
1167
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1168
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1169
+ of shape `(batch_size, sequence_length)`.
1170
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1171
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1172
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1173
+ model's internal embedding lookup matrix.
1174
+ use_cache (`bool`, *optional*):
1175
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1176
+ `past_key_values`).
1177
+ output_attentions (`bool`, *optional*):
1178
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1179
+ tensors for more detail.
1180
+ output_hidden_states (`bool`, *optional*):
1181
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1182
+ more detail.
1183
+ return_dict (`bool`, *optional*):
1184
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1185
+ """
1186
+
1187
+
1188
+ @add_start_docstrings(
1189
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
1190
+ QWEN2_START_DOCSTRING,
1191
+ )
1192
+ class Qwen2Model(Qwen2PreTrainedModel):
1193
+ """
1194
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
1195
+
1196
+ Args:
1197
+ config: Qwen2Config
1198
+ """
1199
+
1200
+ def __init__(self, config: Qwen2Config):
1201
+ super().__init__(config)
1202
+ self.padding_idx = config.pad_token_id
1203
+ self.vocab_size = config.vocab_size
1204
+
1205
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1206
+
1207
+ # BEACON: add beacon embedding
1208
+ self.beacon_embed_tokens = nn.Embedding(1, config.hidden_size, self.padding_idx)
1209
+ self.beacon_embed_tokens._is_hf_initialized = True
1210
+
1211
+ self.layers = nn.ModuleList(
1212
+ [Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1213
+ )
1214
+ self._attn_implementation = config._attn_implementation
1215
+ self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1216
+
1217
+ self.gradient_checkpointing = False
1218
+ # Initialize weights and apply final processing
1219
+ self.post_init()
1220
+
1221
+ def _init_beacon_embed(self, missing_keys):
1222
+ """Initialize the beacon token embedding with that of the eos token."""
1223
+ if is_deepspeed_zero3_enabled():
1224
+ import deepspeed
1225
+ params = [self.beacon_embed_tokens.weight, self.embed_tokens.weight]
1226
+ with deepspeed.zero.GatheredParameters(params, modifier_rank=0):
1227
+ # deepspeed will initialize the parameters to zero
1228
+ if (self.beacon_embed_tokens.weight == 0).all():
1229
+ if self.config.beacon_embed_init == "bos":
1230
+ self.beacon_embed_tokens.weight.data[:] = self.embed_tokens.weight.data[self.config.bos_token_id]
1231
+ elif self.config.beacon_embed_init == "eos":
1232
+ if isinstance(self.config.eos_token_id, list):
1233
+ eos_token_id = self.config.eos_token_id[0]
1234
+ else:
1235
+ eos_token_id = self.config.eos_token_id
1236
+ self.beacon_embed_tokens.weight.data[:] = self.embed_tokens.weight.data[eos_token_id]
1237
+ else:
1238
+ raise NotImplementedError(f"Make sure beacon_embed_init is either eos or bos, found {self.config.beacon_embed_init}")
1239
+ else:
1240
+ if any("beacon_embed_tokens" in missing_key for missing_key in missing_keys):
1241
+ if self.config.beacon_embed_init == "bos":
1242
+ self.beacon_embed_tokens.weight.data[:] = self.embed_tokens.weight.data[self.config.bos_token_id]
1243
+ elif self.config.beacon_embed_init == "eos":
1244
+ if isinstance(self.config.eos_token_id, list):
1245
+ eos_token_id = self.config.eos_token_id[0]
1246
+ else:
1247
+ eos_token_id = self.config.eos_token_id
1248
+ self.beacon_embed_tokens.weight.data[:] = self.embed_tokens.weight.data[eos_token_id]
1249
+ else:
1250
+ raise NotImplementedError(f"Make sure beacon_embed_init is either eos or bos, found {self.config.beacon_embed_init}")
1251
+
1252
+ def get_input_embeddings(self):
1253
+ return self.embed_tokens
1254
+
1255
+ def set_input_embeddings(self, value):
1256
+ self.embed_tokens = value
1257
+
1258
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1259
+ def forward(
1260
+ self,
1261
+ input_ids: torch.LongTensor = None,
1262
+ attention_mask: Optional[torch.Tensor] = None,
1263
+ position_ids: Optional[torch.LongTensor] = None,
1264
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1265
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1266
+ use_cache: Optional[bool] = None,
1267
+ output_attentions: Optional[bool] = None,
1268
+ output_hidden_states: Optional[bool] = None,
1269
+ return_dict: Optional[bool] = None,
1270
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1271
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1272
+ output_hidden_states = (
1273
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1274
+ )
1275
+ # BEACON: always use cache
1276
+ use_cache = True
1277
+
1278
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1279
+
1280
+ # retrieve input_ids and inputs_embeds
1281
+ if input_ids is not None and inputs_embeds is not None:
1282
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1283
+ elif input_ids is not None:
1284
+ batch_size, seq_length = input_ids.shape[:2]
1285
+ elif inputs_embeds is not None:
1286
+ batch_size, seq_length = inputs_embeds.shape[:2]
1287
+ else:
1288
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1289
+
1290
+ past_key, past_value, beacon_size, beacon_indices = past_key_values[0]
1291
+
1292
+ # BEACON: separately embed ordinal tokens and beacon tokens because ordinal tokens do not receive gradients
1293
+ if beacon_size > 0:
1294
+ # NOTE: when beacon_pos == "interleave", the beacon_indices points to all beacon tokens in the current window (cached activations + input_ids), so we shall slice out the part corresponding to the input_ids
1295
+ cur_beacon_indices = beacon_indices[-input_ids.shape[1]:]
1296
+
1297
+ ordinal_input_ids = input_ids[:, cur_beacon_indices == 0]
1298
+ beacon_input_ids = input_ids[:, cur_beacon_indices > 0]
1299
+ ordinal_inputs_embeds = self.embed_tokens(ordinal_input_ids)
1300
+ beacon_input_embeds = self.beacon_embed_tokens(beacon_input_ids - self.config.vocab_size)
1301
+ # create a new embedding tensor
1302
+ inputs_embeds = beacon_input_embeds.new_zeros(*input_ids.shape, beacon_input_embeds.shape[-1])
1303
+ inputs_embeds[:, cur_beacon_indices == 0] = ordinal_inputs_embeds
1304
+ inputs_embeds[:, cur_beacon_indices > 0] = beacon_input_embeds
1305
+
1306
+ else:
1307
+ inputs_embeds = self.embed_tokens(input_ids)
1308
+
1309
+ # embed positions
1310
+ hidden_states = inputs_embeds
1311
+
1312
+ # print(f"input_ids: {input_ids}")
1313
+ # print(f"beacon_indices: {beacon_indices}")
1314
+ # print(f"position_ids: {position_ids}")
1315
+ # print(f"attention_mask:\n{attention_mask == 0}")
1316
+ # x = input()
1317
+ # if x == "s":
1318
+ # return
1319
+
1320
+ # decoder layers
1321
+ all_hidden_states = () if output_hidden_states else None
1322
+ all_self_attns = () if output_attentions else None
1323
+ # BEACON: still use tuple to organize cache
1324
+ next_decoder_cache = () if use_cache else None
1325
+
1326
+ for idx, decoder_layer in enumerate(self.layers):
1327
+ if output_hidden_states:
1328
+ all_hidden_states += (hidden_states,)
1329
+
1330
+ # BEACON: slice out the past_key_value of the corresponding layer
1331
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
1332
+
1333
+ if self.gradient_checkpointing and self.training:
1334
+ layer_outputs = self._gradient_checkpointing_func(
1335
+ decoder_layer.__call__,
1336
+ hidden_states,
1337
+ attention_mask,
1338
+ position_ids,
1339
+ past_key_value,
1340
+ output_attentions,
1341
+ use_cache,
1342
+ )
1343
+ else:
1344
+ layer_outputs = decoder_layer(
1345
+ hidden_states,
1346
+ attention_mask=attention_mask,
1347
+ position_ids=position_ids,
1348
+ past_key_value=past_key_value,
1349
+ output_attentions=output_attentions,
1350
+ use_cache=use_cache,
1351
+ )
1352
+
1353
+ hidden_states = layer_outputs[0]
1354
+
1355
+ if use_cache:
1356
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
1357
+
1358
+ if output_attentions:
1359
+ all_self_attns += (layer_outputs[1],)
1360
+
1361
+ hidden_states = self.norm(hidden_states)
1362
+
1363
+ # add hidden states from the last decoder layer
1364
+ if output_hidden_states:
1365
+ all_hidden_states += (hidden_states,)
1366
+
1367
+ next_cache = next_decoder_cache if use_cache else None
1368
+
1369
+ if not return_dict:
1370
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1371
+ return BaseModelOutputWithPast(
1372
+ last_hidden_state=hidden_states,
1373
+ past_key_values=next_cache,
1374
+ hidden_states=all_hidden_states,
1375
+ attentions=all_self_attns,
1376
+ )
1377
+
1378
+
1379
+ class Qwen2ForCausalLM(Qwen2PreTrainedModel):
1380
+ _tied_weights_keys = ["lm_head.weight"]
1381
+
1382
+ def __init__(self, config):
1383
+ super().__init__(config)
1384
+ self.model = Qwen2Model(config)
1385
+ self.vocab_size = config.vocab_size
1386
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1387
+ # Initialize weights and apply final processing
1388
+ self.post_init()
1389
+
1390
+ def get_input_embeddings(self):
1391
+ return self.model.embed_tokens
1392
+
1393
+ def set_input_embeddings(self, value):
1394
+ self.model.embed_tokens = value
1395
+
1396
+ def get_output_embeddings(self):
1397
+ return self.lm_head
1398
+
1399
+ def set_output_embeddings(self, new_embeddings):
1400
+ self.lm_head = new_embeddings
1401
+
1402
+ def set_decoder(self, decoder):
1403
+ self.model = decoder
1404
+
1405
+ def get_decoder(self):
1406
+ return self.model
1407
+
1408
+ @classmethod
1409
+ def from_pretrained(cls, *args, **kwargs):
1410
+ """Override the default from_pretrained to extend vocab size according to beacon_size."""
1411
+ kwargs.update(output_loading_info=True)
1412
+ model, loading_info = super().from_pretrained(*args, **kwargs)
1413
+
1414
+ # NOTE: set memory after from_pretrained because there may be another transformer model inside the Memory object, which may cause weird erros during loading
1415
+ config = model.config
1416
+ model.memory = Memory(
1417
+ model_config=config,
1418
+ k_seq_dim=2,
1419
+ v_seq_dim=2,
1420
+ )
1421
+
1422
+ missing_keys = loading_info["missing_keys"]
1423
+ # NOTE: the beacon parameters may or may not be loaded from the checkpoint
1424
+ # if it is loaded from the checkpoint, we should not re-initilize it
1425
+ model.model._init_beacon_embed(missing_keys)
1426
+ # initialize weights of possible q,k,v,o,mlp
1427
+ for layer in model.model.layers:
1428
+ layer.self_attn._init_beacon_proj(missing_keys)
1429
+ layer.mlp._init_beacon_proj(missing_keys)
1430
+
1431
+ return model
1432
+
1433
+ def _native_forward(
1434
+ self,
1435
+ input_ids: torch.LongTensor = None,
1436
+ attention_mask: Optional[torch.Tensor] = None,
1437
+ position_ids: Optional[torch.LongTensor] = None,
1438
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1439
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1440
+ labels: Optional[torch.LongTensor] = None,
1441
+ shift_labels: Optional[bool] = True,
1442
+ use_cache: Optional[bool] = None,
1443
+ output_attentions: Optional[bool] = None,
1444
+ output_hidden_states: Optional[bool] = None,
1445
+ return_dict: Optional[bool] = None,
1446
+ ) -> Union[Tuple, BeaconModelOutput]:
1447
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1448
+ output_hidden_states = (
1449
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1450
+ )
1451
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1452
+
1453
+ # when we directly call _native_forward, the past_key_values would be None
1454
+ if past_key_values is None:
1455
+ # NOTE: set beacon size to 0 to avoid using any beacon parameters, see Qwen2Attention.forward
1456
+ past_key_values = [(None, None, 0, None) for _ in range(self.config.num_hidden_layers)]
1457
+
1458
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1459
+ outputs = self.model(
1460
+ input_ids=input_ids,
1461
+ attention_mask=attention_mask,
1462
+ position_ids=position_ids,
1463
+ past_key_values=past_key_values,
1464
+ inputs_embeds=inputs_embeds,
1465
+ use_cache=use_cache,
1466
+ output_attentions=output_attentions,
1467
+ output_hidden_states=output_hidden_states,
1468
+ return_dict=return_dict,
1469
+ )
1470
+
1471
+ hidden_states = outputs[0]
1472
+ logits = self.lm_head(hidden_states)
1473
+ logits = logits.float()
1474
+
1475
+ loss = None
1476
+ batch_loss = None
1477
+ valid_token_num = None
1478
+
1479
+ if labels is not None:
1480
+ loss, batch_loss, valid_token_num = compute_loss(logits, labels, shift=shift_labels)
1481
+
1482
+ if not return_dict:
1483
+ output = (logits,) + outputs[1:]
1484
+ return (loss,) + output if loss is not None else output
1485
+
1486
+ return BeaconModelOutput(
1487
+ loss=loss,
1488
+ batch_loss=batch_loss,
1489
+ valid_token_num=valid_token_num,
1490
+ logits=logits,
1491
+ past_key_values=outputs.past_key_values,
1492
+ hidden_states=outputs.hidden_states,
1493
+ attentions=outputs.attentions,
1494
+ )
1495
+
1496
+ def _beacon_forward(self,
1497
+ input_ids: torch.LongTensor = None,
1498
+ attention_mask: Optional[torch.Tensor] = None,
1499
+ position_ids: Optional[torch.LongTensor] = None,
1500
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1501
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1502
+ labels: Optional[torch.LongTensor] = None,
1503
+ use_cache: Optional[bool] = None,
1504
+ output_attentions: Optional[bool] = None,
1505
+ output_hidden_states: Optional[bool] = None,
1506
+ return_dict: Optional[bool] = None,
1507
+ ):
1508
+ # t1 = time.time()
1509
+
1510
+ # initialize cache
1511
+ self.memory.prepare(
1512
+ input_ids=input_ids,
1513
+ attention_mask=attention_mask,
1514
+ labels=labels
1515
+ )
1516
+
1517
+ # t2 = time.time()
1518
+
1519
+ # after the first window, one token at a time
1520
+ while not self.memory.finish:
1521
+
1522
+ # t3 = time.time()
1523
+
1524
+ input_ids, attention_mask, position_ids, past_key_values, labels = self.memory.step()
1525
+
1526
+ # t4 = time.time()
1527
+
1528
+ outputs = self._native_forward(
1529
+ input_ids=input_ids,
1530
+ attention_mask=attention_mask,
1531
+ position_ids=position_ids,
1532
+ past_key_values=past_key_values,
1533
+ inputs_embeds=inputs_embeds,
1534
+ use_cache=use_cache,
1535
+ output_attentions=output_attentions,
1536
+ output_hidden_states=output_hidden_states,
1537
+ return_dict=return_dict,
1538
+ labels=labels,
1539
+ # NOTE: the labels have been shifted so that all tokens in the window have the proper loss
1540
+ shift_labels=False,
1541
+ )
1542
+
1543
+ # t5 = time.time()
1544
+
1545
+ # update past_key_values
1546
+ self.memory.update_memory(outputs.past_key_values)
1547
+
1548
+ # t6 = time.time()
1549
+
1550
+ if labels is not None:
1551
+ # update loss
1552
+ self.memory.update_loss(outputs.batch_loss, outputs.valid_token_num)
1553
+
1554
+ # t7 = time.time()
1555
+
1556
+ # print(f"step time: {t4-t3}, forward time: {t5-t4}, update time: {t6-t5}, loss time: {t7-t6}")
1557
+ # input()
1558
+
1559
+ # t8 = time.time()
1560
+
1561
+ # output loss, past_key_values, and perplexity
1562
+ outputs = self.memory.output(outputs)
1563
+
1564
+ # t9 = time.time()
1565
+
1566
+ # print(f"output time: {t9-t8}")
1567
+ # input()
1568
+
1569
+ return outputs
1570
+
1571
+ def forward(self, **kwargs):
1572
+ """Forward computation over a batch of sequences.
1573
+ """
1574
+ # only allow gradient when training
1575
+ with optional_grad_ctx(with_grad=self.training):
1576
+ # we can disable beacon to use the original mistral
1577
+ if hasattr(self, "_enable_beacon") and self._enable_beacon == False:
1578
+ return self._native_forward(**kwargs)
1579
+ else:
1580
+ return self._beacon_forward(**kwargs)
1581
+
1582
+ def prepare_inputs_for_generation(
1583
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1584
+ ):
1585
+ if past_key_values:
1586
+ input_ids = input_ids[:, -1:]
1587
+
1588
+ position_ids = kwargs.get("position_ids", None)
1589
+ if attention_mask is not None and position_ids is None:
1590
+ # create position_ids on the fly for batch generation
1591
+ position_ids = attention_mask.long().cumsum(-1) - 1
1592
+ position_ids.masked_fill_(attention_mask == 0, 1)
1593
+ if past_key_values:
1594
+ position_ids = position_ids[:, -1].unsqueeze(-1)
1595
+
1596
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1597
+ if inputs_embeds is not None and past_key_values is None:
1598
+ model_inputs = {"inputs_embeds": inputs_embeds}
1599
+ else:
1600
+ model_inputs = {"input_ids": input_ids}
1601
+
1602
+ model_inputs.update(
1603
+ {
1604
+ "position_ids": position_ids,
1605
+ "past_key_values": past_key_values,
1606
+ "use_cache": kwargs.get("use_cache"),
1607
+ "attention_mask": attention_mask,
1608
+ }
1609
+ )
1610
+ return model_inputs
1611
+
1612
+ @staticmethod
1613
+ def _reorder_cache(past_key_values, beam_idx):
1614
+ reordered_past = ()
1615
+ for layer_past in past_key_values:
1616
+ reordered_past += (
1617
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1618
+ )
1619
+ return reordered_past
modeling_utils.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from tqdm import tqdm
4
+ from dataclasses import dataclass
5
+ from contextlib import nullcontext
6
+ from typing import Mapping, Optional, Tuple
7
+ from accelerate import Accelerator
8
+ from collections import defaultdict
9
+ from transformers.modeling_outputs import BaseModelOutputWithPast
10
+
11
+
12
+ def optional_grad_ctx(with_grad=False):
13
+ if with_grad:
14
+ return nullcontext()
15
+ else:
16
+ return torch.no_grad()
17
+
18
+ def move_to_device(data, device):
19
+ """
20
+ Prepares one `data` before feeding it to the model, be it a tensor or a nested list/dictionary of tensors.
21
+ """
22
+ if isinstance(data, Mapping):
23
+ return type(data)({k: move_to_device(v, device) for k, v in data.items()})
24
+ elif isinstance(data, (tuple, list)):
25
+ return type(data)(move_to_device(v, device) for v in data)
26
+ elif isinstance(data, torch.Tensor):
27
+ kwargs = {"device": device}
28
+ return data.to(**kwargs)
29
+ else:
30
+ return data
31
+
32
+ def compute_loss(logits, labels, shift=False):
33
+ """
34
+ Returns:
35
+ token_loss: batch_size, seq_length
36
+ """
37
+ if shift:
38
+ logits = logits[:, :-1, :].contiguous()
39
+ labels = labels[:, 1:].contiguous()
40
+
41
+ labels = labels.to(logits.device)
42
+ batch_size = logits.shape[0]
43
+
44
+ # NOTE: the loss on -100 labels is 0 by default
45
+ token_loss = torch.nn.functional.cross_entropy(
46
+ logits.flatten(0, 1),
47
+ labels.reshape(-1),
48
+ reduction="none"
49
+ ).reshape(batch_size, -1) # batch_size, seq_len
50
+
51
+ # print(token_loss)
52
+
53
+ valid_token_num = (labels != -100).sum(-1) # batch_size
54
+ all_valid_token_num = valid_token_num.sum()
55
+
56
+ if all_valid_token_num > 0:
57
+ loss = token_loss.sum() / valid_token_num.sum()
58
+ else:
59
+ loss = token_loss.sum()
60
+
61
+ batch_loss = token_loss.sum(-1) / valid_token_num
62
+ # prevent nan
63
+ if (valid_token_num == 0).any():
64
+ batch_loss = batch_loss.masked_fill(valid_token_num == 0, 0.)
65
+
66
+ return loss, batch_loss, valid_token_num
67
+
68
+
69
+ @torch.no_grad()
70
+ def evaluate_perplexity(model, dataloader, accelerator:Optional[Accelerator]=None):
71
+ if accelerator is not None and type(dataloader) == torch.utils.data.DataLoader:
72
+ # if the dataloader has been prepared, we shall not prepare it twice, especially in case of deepspeed
73
+ dataloader = accelerator.prepare(dataloader)
74
+
75
+ # if accelerator.process_index == 0:
76
+ # for name, x in model.named_parameters():
77
+ # print(f"{name: ^80} {x.dtype}")
78
+
79
+ all_loss = defaultdict(list)
80
+ for i, x in enumerate(tqdm(dataloader, desc="Computing Perplexity")):
81
+ # NOTE: important to reset memory for every batch
82
+ if hasattr(model, "memory"):
83
+ model.memory.reset()
84
+
85
+ # the seq id
86
+ index = x.pop("index")
87
+ # length is used to group training data, no use here
88
+ length = x.pop("length", None)
89
+
90
+ output = model(**x)
91
+
92
+ # NOTE: we need the loss for each element in the batch for accurate computation, because the number of valid tokens may differ among elements
93
+ if hasattr(output, "batch_loss"):
94
+ # output from our model has batch_loss by default
95
+ batch_loss = output.batch_loss
96
+ valid_token_num = output.valid_token_num
97
+ else:
98
+ # output from other models does not
99
+ loss, batch_loss, valid_token_num = compute_loss(output.logits, x["labels"], shift=True)
100
+
101
+ index = index.tolist()
102
+ batch_loss = batch_loss.tolist()
103
+ valid_token_num = valid_token_num.tolist()
104
+
105
+ if accelerator is not None and accelerator.num_processes > 1:
106
+ # num_device * batch_size
107
+ index = accelerator.gather_for_metrics(index)
108
+ batch_loss = accelerator.gather_for_metrics(batch_loss)
109
+ valid_token_num = accelerator.gather_for_metrics(valid_token_num)
110
+
111
+ for _id, _loss, _num in zip(index, batch_loss, valid_token_num):
112
+ # loss times num is the total loss of all valid tokens
113
+ all_loss[_id].append((_loss * _num, _num))
114
+
115
+ all_loss = dict(all_loss)
116
+ for _id, loss_and_num in all_loss.items():
117
+ # sum up the loss for all valid tokens in the entire sequence, and divide the number of valid tokens
118
+ all_loss[_id] = sum([x[0] for x in loss_and_num]) / sum(x[1] for x in loss_and_num)
119
+
120
+ # average across then take exp
121
+ perplexity = math.exp(sum(all_loss.values()) / len(all_loss))
122
+ return perplexity
123
+
124
+
125
+ @torch.no_grad()
126
+ def evaluate_generation(model, dataloader, accelerator:Optional[Accelerator]=None, tokenizer=None, return_new_tokens_only=True, **generation_config):
127
+ if accelerator is not None and type(dataloader) == torch.utils.data.DataLoader:
128
+ # if the dataloader has been prepared, we shall not prepare it twice, especially in case of deepspeed
129
+ dataloader = accelerator.prepare(dataloader)
130
+
131
+ all_indices = []
132
+ all_outputs = []
133
+
134
+ index = 0
135
+
136
+ for i, x in enumerate(tqdm(dataloader, desc="Computing Generation")):
137
+ # if i > 3:
138
+ # break
139
+
140
+ # NOTE: important to reset memory for every batch
141
+ if hasattr(model, "memory"):
142
+ model.memory.reset()
143
+
144
+ # length is used to group training data, no use here
145
+ length = x.pop("length", None)
146
+
147
+ # if indices are None, we use batch size
148
+ indices = x.pop("index", None)
149
+ if indices is None:
150
+ indices = list(range(index, index + x['input_ids'].shape[0]))
151
+ index += x['input_ids'].shape[0]
152
+ else:
153
+ indices = indices.tolist()
154
+
155
+ outputs = model.generate(**x, **generation_config)
156
+ if return_new_tokens_only:
157
+ start_idx = x["input_ids"].shape[1]
158
+ outputs = outputs[:, start_idx:]
159
+
160
+ outputs = tokenizer.batch_decode(outputs, skip_special_tokens=True)
161
+
162
+ if accelerator is not None and accelerator.num_processes > 1:
163
+ outputs = accelerator.gather_for_metrics(outputs)
164
+ indices = accelerator.gather_for_metrics(indices)
165
+
166
+ outputs = outputs
167
+ indices = indices
168
+ all_indices.extend(indices)
169
+ all_outputs.extend(outputs)
170
+
171
+ return all_indices, all_outputs
172
+
173
+
174
+ @torch.no_grad()
175
+ def evaluate_nll(model, dataloader, accelerator:Optional[Accelerator]=None):
176
+ if accelerator is not None and type(dataloader) == torch.utils.data.DataLoader:
177
+ # if the dataloader has been prepared, we shall not prepare it twice, especially in case of deepspeed
178
+ dataloader = accelerator.prepare(dataloader)
179
+
180
+ # if accelerator.process_index == 0:
181
+ # for name, x in model.named_parameters():
182
+ # print(f"{name: ^80} {x.dtype}")
183
+
184
+ all_loss = defaultdict(list)
185
+ for i, x in enumerate(tqdm(dataloader, desc="Computing Perplexity")):
186
+ # NOTE: important to reset memory for every batch
187
+ if hasattr(model, "memory"):
188
+ model.memory.reset()
189
+
190
+ # the seq id
191
+ index = x.pop("index")
192
+ # length is used to group training data, no use here
193
+ length = x.pop("length", None)
194
+
195
+ output = model(**x)
196
+
197
+ # NOTE: we need the loss for each element in the batch for accurate computation, because the number of valid tokens may differ among elements
198
+ if hasattr(output, "batch_loss"):
199
+ # output from our model has batch_loss by default
200
+ batch_loss = output.batch_loss
201
+ valid_token_num = output.valid_token_num
202
+ else:
203
+ # output from other models does not
204
+ loss, batch_loss, valid_token_num = compute_loss(output.logits, x["labels"], shift=True)
205
+
206
+ if accelerator is not None and accelerator.num_processes > 1:
207
+ # num_device * batch_size
208
+ index = accelerator.gather_for_metrics(index)
209
+ batch_loss = accelerator.gather_for_metrics(batch_loss)
210
+ valid_token_num = accelerator.gather_for_metrics(valid_token_num)
211
+
212
+ for _id, _loss in zip(index.tolist(), batch_loss.tolist()):
213
+ # loss times num is the total loss of all valid tokens
214
+ all_loss[_id].append(_loss)
215
+
216
+ return all_loss
217
+
218
+
219
+
220
+ @dataclass
221
+ class BeaconModelOutput(BaseModelOutputWithPast):
222
+ loss: Optional[torch.FloatTensor] = None
223
+ batch_loss: Optional[torch.FloatTensor] = None
224
+ valid_token_num: Optional[torch.LongTensor] = None
225
+ logits: torch.FloatTensor = None
226
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
227
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
228
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
special_tokens_map.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>"
5
+ ],
6
+ "eos_token": {
7
+ "content": "<|im_end|>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false
12
+ },
13
+ "pad_token": {
14
+ "content": "<|endoftext|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false
19
+ }
20
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "151643": {
5
+ "content": "<|endoftext|>",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "151644": {
13
+ "content": "<|im_start|>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ },
20
+ "151645": {
21
+ "content": "<|im_end|>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": true
27
+ }
28
+ },
29
+ "additional_special_tokens": [
30
+ "<|im_start|>",
31
+ "<|im_end|>"
32
+ ],
33
+ "bos_token": null,
34
+ "chat_template": "{% for message in messages %}{% if loop.first and messages[0]['role'] != 'system' %}{{ '<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n' }}{% endif %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}",
35
+ "clean_up_tokenization_spaces": false,
36
+ "eos_token": "<|im_end|>",
37
+ "errors": "replace",
38
+ "model_max_length": 131072,
39
+ "pad_token": "<|endoftext|>",
40
+ "padding_side": "left",
41
+ "split_special_tokens": false,
42
+ "tokenizer_class": "Qwen2Tokenizer",
43
+ "unk_token": null
44
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff