qhjqhj00 commited on
Commit
74ae950
1 Parent(s): 6510631
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,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/share/qhj/Activation-Beacon/outputs/beacon-qwen2-full_coverage-interleave-2048_2048-2,4,8,16,32-step_random-qkv-redpajama/checkpoint-11436",
3
+ "architectures": [
4
+ "Qwen2ForCausalLM"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_qwen2.Qwen2Config",
9
+ "AutoModelForCausalLM": "modeling_qwen2.Qwen2ForCausalLM"
10
+ },
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
+ ],
26
+ "beacon_ratio_mix": "step-random",
27
+ "beacon_sink_size": 0,
28
+ "beacon_stride": 2048,
29
+ "beacon_window": 2048,
30
+ "bos_token_id": 151643,
31
+ "eos_token_id": 151645,
32
+ "hidden_act": "silu",
33
+ "hidden_size": 3584,
34
+ "initializer_range": 0.02,
35
+ "intermediate_size": 18944,
36
+ "max_position_embeddings": 32768,
37
+ "max_window_layers": 28,
38
+ "model_type": "qwen2",
39
+ "num_attention_heads": 28,
40
+ "num_hidden_layers": 28,
41
+ "num_key_value_heads": 4,
42
+ "rms_norm_eps": 1e-06,
43
+ "rope_scaling": null,
44
+ "rope_theta": 1000000.0,
45
+ "sliding_window": 131072,
46
+ "tie_word_embeddings": false,
47
+ "torch_dtype": "bfloat16",
48
+ "transformers_version": "4.43.1",
49
+ "use_cache": true,
50
+ "use_sliding_window": false,
51
+ "vocab_size": 152064
52
+ }
configuration_qwen2.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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=1024,
119
+ beacon_stride=1024,
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
+ beacon_accum=True,
130
+ **kwargs,
131
+ ):
132
+ self.vocab_size = vocab_size
133
+ self.max_position_embeddings = max_position_embeddings
134
+ self.hidden_size = hidden_size
135
+ self.intermediate_size = intermediate_size
136
+ self.num_hidden_layers = num_hidden_layers
137
+ self.num_attention_heads = num_attention_heads
138
+ self.use_sliding_window = use_sliding_window
139
+ self.sliding_window = sliding_window
140
+ self.max_window_layers = max_window_layers
141
+ self.rope_scaling = rope_scaling
142
+
143
+ # for backward compatibility
144
+ if num_key_value_heads is None:
145
+ num_key_value_heads = num_attention_heads
146
+
147
+ self.num_key_value_heads = num_key_value_heads
148
+ self.hidden_act = hidden_act
149
+ self.initializer_range = initializer_range
150
+ self.rms_norm_eps = rms_norm_eps
151
+ self.use_cache = use_cache
152
+ self.rope_theta = rope_theta
153
+ self.attention_dropout = attention_dropout
154
+
155
+ self.beacon_window = beacon_window
156
+ self.beacon_stride = beacon_stride
157
+ self.beacon_attn = beacon_attn
158
+ self.beacon_ratio = beacon_ratio
159
+ self.beacon_ratio_mix = beacon_ratio_mix
160
+ self.beacon_param = beacon_param
161
+ self.beacon_embed_init = beacon_embed_init
162
+ self.beacon_sink_size = beacon_sink_size
163
+ self.beacon_attend_prev = beacon_attend_prev
164
+ self.beacon_pos = beacon_pos
165
+ self.beacon_parallel_window = beacon_parallel_window
166
+ self.beacon_accum = beacon_accum
167
+
168
+ super().__init__(
169
+ tie_word_embeddings=tie_word_embeddings,
170
+ **kwargs,
171
+ )
generation_config.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 151643,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 151645,
6
+ 151643
7
+ ],
8
+ "pad_token_id": 151643,
9
+ "repetition_penalty": 1.05,
10
+ "temperature": 0.7,
11
+ "top_k": 20,
12
+ "top_p": 0.8,
13
+ "transformers_version": "4.43.1"
14
+ }
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:6a965d8b29f5fcd3f8c3cb045bcfd4e26922cda09e9668c9950613e2a74e4051
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:542e733db79297f2a97e949ca21cabe4ffcd01ea2734cf31f42fd0b9e212f536
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:8cf8c07295981aeba4ee35554d3ad9e0946a4a4fc4f82cb99e88a598e9041e40
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
+ }
model_args.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"model_cache_dir": null, "dataset_cache_dir": null, "data_root": "/data/long-llm", "train_data": ["/share/qhj/rags/data/long_context/train/0830.all.30k.jsonl"], "eval_data": null, "model_name_or_path": "/share/qhj/Activation-Beacon/outputs/beacon-qwen2-full_coverage-interleave-2048_2048-2,4,8,16,32-step_random-qkv-redpajama/checkpoint-11436", "padding_side": "left", "no_use_fast": false, "access_token": null, "attn_impl": "flash_attention_2", "max_length": 40000, "chat_template": "qwen", "max_position_embeddings": null, "mistral_sliding_window": null, "rope_theta": null, "rope_method": null, "rope_factor": 1.0, "lora": null, "lora_unload": true, "load_in_4_bit": false, "dtype": "bf16", "device_map": null, "batch_size": 1, "cpu": false, "enable_tp": false, "enable_vllm": false, "vllm_mem": 0.9, "vllm_tp": 1, "vllm_len": null, "vllm_disable_ar": false, "enable_beacon": true, "beacon_window": 2048, "beacon_stride": 2048, "beacon_attn": "full-coverage", "beacon_ratio": [2, 4, 8], "beacon_ratio_mix": "step-random", "beacon_param": ["q", "k", "v"], "beacon_embed_init": "eos", "beacon_sink_size": 0, "beacon_attend_prev": true, "beacon_pos": "interleave", "beacon_parallel_window": null, "retrieval_method": null, "retrieval_topk": null, "retrieval_key_length": null, "max_new_tokens": null, "do_sample": null, "temperature": null, "top_p": null}
modeling_beacon.py ADDED
@@ -0,0 +1,1143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import time
4
+ import numpy as np
5
+ import torch.distributed as dist
6
+ from copy import deepcopy
7
+ from transformers.utils import logging
8
+ from transformers import AutoTokenizer
9
+ from itertools import cycle
10
+ from typing import List
11
+
12
+ logger = logging.get_logger(__name__)
13
+
14
+
15
+ class Memory(torch.nn.Module):
16
+ def __init__(
17
+ self,
18
+ model_config,
19
+ k_seq_dim:int=2,
20
+ v_seq_dim:int=2,
21
+ ):
22
+ """Setup necessary attributes."""
23
+ super().__init__()
24
+
25
+ self.config = model_config
26
+
27
+ # initialize necessary parameters
28
+ self.k_seq_dim = k_seq_dim
29
+ self.v_seq_dim = v_seq_dim
30
+ self.rng = np.random.default_rng(42)
31
+
32
+ self._post_validation()
33
+ self.reset()
34
+
35
+ @property
36
+ def beacon_token(self):
37
+ return self.config.vocab_size
38
+
39
+ def _post_validation(self, verbose=True):
40
+ 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}!"
41
+ for ratio in self.config.beacon_ratio:
42
+ assert ratio >= 0, f"Make sure all beacon ratios are greater than or equal to 0, found {self.config.beacon_ratio}!"
43
+ assert self.config.beacon_attn in ["segmentation", "step-expansion", "full-coverage"], f"beacon_attn {self.config.beacon_attn} not implemented!"
44
+ 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!"
45
+ # assert self.config.beacon_pos in ["append", "interleave"], f"beacon_pos {self.config.beacon_pos} not implemented!"
46
+ if self.config.beacon_pos == "interleave":
47
+ assert self.config.beacon_window == self.config.beacon_stride, f"Make sure the beacon_window equals to beacon_stride when using interleaving mode."
48
+ if self.config.beacon_parallel_window > 1:
49
+ assert self.config._attn_implementation != "flash_attention_2", f"Currently parallel window does not support flash_attention_2!"
50
+
51
+ self._cpu = torch.device("cpu")
52
+
53
+ if verbose:
54
+ 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})..."
55
+ logger.info(info)
56
+
57
+ def set(self, verbose=True, **kwargs):
58
+ """
59
+ Set attributes out of the constructor.
60
+ """
61
+ for k, v in kwargs.items():
62
+ setattr(self.config, k, v)
63
+ self._post_validation(verbose=verbose)
64
+
65
+ def reset(self, **kwargs):
66
+ """Initialize attributes for a new sequence."""
67
+ # the cursor pointing to the start of the current window
68
+ self.start_idx = 0
69
+ # the cursor pointing to the end of the current window
70
+ self.end_idx = 0
71
+ # the beacon sizes of all strides
72
+ self.all_beacon_sizes = []
73
+ # the loss per batch
74
+ self.batch_loss = None
75
+ # the valid token number per batch
76
+ self.valid_token_num = None
77
+ # the step index for processing the input_ids
78
+ self.step_idx = 0
79
+ # used in set_compression_ratio
80
+ self.compression_ratio = None
81
+ # the previous inputs is a full window or not, defaults to True
82
+ self.is_full_window = True
83
+ # the number of raw activations to preserve in update_memory (only useful when beacon_stride < beacon_window)
84
+ self.raw_size_to_cache = 0
85
+
86
+ # the number of tokens in previous stride that should be compressed by the upcoming beacon
87
+ self.interleave_remainder = 0
88
+ # compression ratio for the unfinished window
89
+ self.interleave_compression_ratio = None
90
+ self.beacon_indices = None
91
+
92
+ self.all_input_ids = None
93
+ self.all_attention_mask = None
94
+ self.all_labels = None
95
+
96
+ # NOTE: will be reset in prepare()
97
+ self.beacon_skip_first = None
98
+ self.beacon_skip_last = None
99
+
100
+ # the attention sink activations
101
+ self.sink_activations = [(None, None) for _ in range(self.config.num_hidden_layers)]
102
+ # the beacon activations
103
+ self.beacon_activations = [(None, None) for _ in range(self.config.num_hidden_layers)]
104
+ # the raw activations of recent tokens
105
+ self.raw_activations = [(None, None) for _ in range(self.config.num_hidden_layers)]
106
+
107
+ # NOTE: in case we want to resume the memory from a particular state
108
+ for k, v in kwargs.items():
109
+ # NOTE: deepcopy to untie the memory state and the model memory
110
+ setattr(self, deepcopy(k), deepcopy(v))
111
+
112
+ def export(self):
113
+ """Export all necessary attributes of the memory module."""
114
+ return {
115
+ "start_idx": self.start_idx,
116
+ "end_idx": self.end_idx,
117
+ "all_beacon_sizes": self.all_beacon_sizes,
118
+ "batch_loss": self.batch_loss,
119
+ "valid_token_num": self.valid_token_num,
120
+ "step_idx": self.step_idx,
121
+ "compression_ratio": self.compression_ratio,
122
+ "is_full_window": self.is_full_window,
123
+ "raw_size_to_cache": self.raw_size_to_cache,
124
+ "interleave_remainder": self.interleave_remainder,
125
+ "interleave_compression_ratio": self.interleave_compression_ratio,
126
+ "beacon_indices": self.beacon_indices,
127
+ "all_input_ids": self.all_input_ids,
128
+ "all_attention_mask": self.all_attention_mask,
129
+ "all_labels": self.all_labels,
130
+ "beacon_skip_first": self.beacon_skip_first,
131
+ "beacon_skip_last": self.beacon_skip_last,
132
+ # NOTE: deepcopy to untie the memory state and the model memory
133
+ "sink_activations": deepcopy(self.sink_activations),
134
+ "beacon_activations": deepcopy(self.beacon_activations),
135
+ "raw_activations": deepcopy(self.raw_activations),
136
+ }
137
+
138
+ @property
139
+ def all_sequence_length(self):
140
+ if self.all_input_ids is None:
141
+ return 0
142
+ else:
143
+ return self.all_input_ids.shape[1]
144
+
145
+ @property
146
+ def batch_size(self):
147
+ if self.all_input_ids is None:
148
+ return 0
149
+ else:
150
+ return self.all_input_ids.shape[0]
151
+
152
+ @property
153
+ def finish(self):
154
+ is_finish = self.end_idx == self.all_sequence_length
155
+ return is_finish
156
+
157
+ @property
158
+ def dtype(self):
159
+ return self.config.torch_dtype
160
+
161
+ @property
162
+ def min_value(self):
163
+ return torch.finfo(self.dtype).min
164
+
165
+ @property
166
+ def max_position_embeddings(self):
167
+ max_position_embeddings = self.config.max_position_embeddings
168
+ if getattr(self.config, "rope_scaling", None) is not None:
169
+ scaling_factor = self.config.rope_scaling["factor"]
170
+ max_position_embeddings = max_position_embeddings * scaling_factor
171
+ return max_position_embeddings
172
+
173
+ @property
174
+ def beacon_window(self):
175
+ if (
176
+ self.beacon_skip_last is not None
177
+ and self.start_idx < self.beacon_skip_last
178
+ and self.start_idx + self.config.beacon_window > self.beacon_skip_last
179
+ ):
180
+ return self.beacon_skip_last - self.start_idx
181
+ else:
182
+ return self.config.beacon_window
183
+
184
+ @property
185
+ def beacon_stride(self):
186
+ if (
187
+ self.beacon_skip_last is not None
188
+ and self.start_idx < self.beacon_skip_last
189
+ and self.start_idx + self.config.beacon_window > self.beacon_skip_last
190
+ ):
191
+ return self.beacon_skip_last - self.start_idx
192
+ else:
193
+ return self.config.beacon_stride
194
+
195
+ def get_memory_size(self):
196
+ """
197
+ Sink memory size, beacon memory size and raw memory size.
198
+ """
199
+ sink_memory_size = 0
200
+ beacon_memory_size = 0
201
+ raw_memory_size = 0
202
+ if self.sink_activations[0][0] is not None:
203
+ sink_memory_size += self.sink_activations[0][0].shape[self.k_seq_dim]
204
+ if self.beacon_activations[0][0] is not None:
205
+ beacon_memory_size += self.beacon_activations[0][0].shape[self.k_seq_dim]
206
+ if self.raw_activations[0][0] is not None:
207
+ raw_memory_size += self.raw_activations[0][0].shape[self.k_seq_dim]
208
+ return sink_memory_size, beacon_memory_size, raw_memory_size
209
+
210
+ def prepare(self, input_ids, attention_mask, labels, skip_first=None, skip_last=None):
211
+ """
212
+ Prepare inputs for the model. These inputs belong to the same sequence.
213
+ """
214
+ # assert input_ids.shape[0] == 1, "Make sure the batch size is 1!"
215
+ # assert attention_mask is None or (attention_mask == 1).all(), "Make sure there is no padding!"
216
+
217
+ self._device = input_ids.device
218
+
219
+ # accumulate input_ids
220
+ if self.all_input_ids is None:
221
+ self.all_input_ids = input_ids.cpu()
222
+ else:
223
+ self.all_input_ids = torch.cat([self.all_input_ids, input_ids.cpu()], dim=1)
224
+
225
+ # accumulate attention_mask
226
+ if attention_mask is None:
227
+ attention_mask = torch.ones_like(input_ids, device=torch.device("cpu"))
228
+ if self.all_attention_mask is None:
229
+ self.all_attention_mask = attention_mask.cpu()
230
+ else:
231
+ self.all_attention_mask = torch.cat([self.all_attention_mask, attention_mask.cpu()], dim=1)
232
+
233
+ # accumulate labels if exisits
234
+ if labels is not None:
235
+ # rotate labels in advance so that the loss of the last token is not ignored in every window
236
+ labels = torch.cat([labels[:, 1:].cpu(), torch.tensor([-100]).expand(labels.shape[0], 1)], dim=1)
237
+ if self.all_labels is None:
238
+ self.all_labels = labels.cpu()
239
+ else:
240
+ self.all_labels = torch.cat([self.all_labels, labels], dim=1)
241
+ 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}!"
242
+
243
+ # how many tokens to skip at the beginning of the sequence? (They will be packed in a single chunk and processed by the model, after which their activations will be cached in sink_activations.)
244
+ if skip_first is not None:
245
+ assert self.config.beacon_parallel_window == 1, f"Make sure the parallel window is set to 1 when using beacon_skip!"
246
+ assert self.config.beacon_window == self.config.beacon_stride, f"Make sure the beacon_window equals to beacon_stride when using beacon_skip."
247
+ assert self.config.beacon_sink_size == 0, f"Make sure the beacon_sink_size is set to 0 when using beacon_skip!"
248
+ # stop compression after how many tokens
249
+ if skip_last is not None:
250
+ skip_first = skip_first if skip_first is not None else 0
251
+ # assert (skip_last - skip_first) % self.config.beacon_window == 0, f"skip_last ({skip_last}) - skip_first ({skip_first}) = {skip_last - skip_first} is not divisible by window size {self.config.beacon_window}"
252
+ assert self.config.beacon_sink_size == 0, "Make sure the beacon_sink_size is zero when using skip_last!"
253
+ self.beacon_skip_first = skip_first
254
+ self.beacon_skip_last = skip_last
255
+
256
+ def set_compression_ratio(self, start_idx, end_idx):
257
+ """Choose a condensing ratio from self.config.beacon_ratio"""
258
+ def filter_ratio(ratios, stride):
259
+ valid_ratios = []
260
+ for ratio in ratios:
261
+ # stride must be bigger than condensing ratio because we there must be at least one beacon
262
+ if stride < ratio:
263
+ continue
264
+ # the stride must be evenly divisible by condensing ratio
265
+ if ratio > 0 and (stride % ratio) != 0:
266
+ continue
267
+ # when training, ratio=0 is valid if previous windows contain beacon or later windows contain beacon
268
+ if ratio == 0 and self.training:
269
+ previous_has_zero = -1 in self.all_beacon_sizes
270
+ following_has_nonzero = (start_idx + stride + self.beacon_window) <= self.all_sequence_length
271
+ if previous_has_zero or (not following_has_nonzero):
272
+ continue
273
+ valid_ratios.append(ratio)
274
+ assert len(valid_ratios), f"Cannot find valid condensing ratio (among {ratios}) for stride {stride}!"
275
+ return valid_ratios
276
+
277
+ def get_max_length(ratios):
278
+ max_lengths = []
279
+ for compression_ratio in ratios:
280
+ if compression_ratio > 0:
281
+ # NOTE: here we must use the scaled position embeddings
282
+ max_lengths.append((self.max_position_embeddings - self.beacon_window) * compression_ratio + self.beacon_window)
283
+ else:
284
+ max_lengths.append(self.max_position_embeddings)
285
+ return max_lengths
286
+
287
+ if len(self.config.beacon_ratio) == 1:
288
+ return self.config.beacon_ratio[0]
289
+
290
+ ratio_mix = self.config.beacon_ratio_mix
291
+
292
+ beacon_ratio = filter_ratio(self.config.beacon_ratio, self.beacon_stride)
293
+
294
+ if ratio_mix == "instance-random":
295
+ if self.compression_ratio is None:
296
+ beacon_ratio = self.rng.choice(beacon_ratio).tolist()
297
+ self.compression_ratio = beacon_ratio
298
+ else:
299
+ beacon_ratio = self.compression_ratio
300
+
301
+ elif ratio_mix == "step-random":
302
+ beacon_ratio = self.rng.choice(beacon_ratio).tolist()
303
+
304
+ elif ratio_mix == "sequence":
305
+ if self.compression_ratio is None:
306
+ self.compression_ratio = cycle(beacon_ratio)
307
+ beacon_ratio = next(self.compression_ratio)
308
+
309
+ elif "adapt" in ratio_mix:
310
+ if self.compression_ratio is None:
311
+ future_length = int(ratio_mix.split("-")[1])
312
+ sequence_length = self.all_input_ids.shape[1] + future_length
313
+ max_lengths = get_max_length(beacon_ratio)
314
+ # ascendingly sort the max lengths
315
+ valid_max_lengths_and_indices = [x for x in enumerate(max_lengths) if x[1] >= sequence_length]
316
+ if len(valid_max_lengths_and_indices):
317
+ minimum_length_index = min(valid_max_lengths_and_indices, key=lambda x: x[1])[0]
318
+ # use the minimal possible length for this sequence (the smallest fold ratio)
319
+ beacon_ratio = beacon_ratio[minimum_length_index]
320
+ else:
321
+ beacon_ratio = max(beacon_ratio)
322
+ # 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}.")
323
+ self.compression_ratio = beacon_ratio
324
+ else:
325
+ beacon_ratio = self.compression_ratio
326
+
327
+ return beacon_ratio
328
+
329
+ def step(self):
330
+ # parallel does not support stride < window
331
+ # parallel does not support non-compression
332
+ # the input_ids is not long enough for parallel
333
+ if (
334
+ self.config.beacon_parallel_window > 1
335
+ and self.config.beacon_stride == self.config.beacon_window
336
+ and 0 not in self.config.beacon_ratio
337
+ and self.all_input_ids[:, self.end_idx:].shape[1] >= self.config.beacon_parallel_window * self.config.beacon_window
338
+ ):
339
+ input_ids_list = []
340
+ attention_mask_list = []
341
+ position_ids_list = []
342
+ labels_list = []
343
+
344
+ beacon_size_list = []
345
+ beacon_indices_list = []
346
+
347
+ for i in range(self.config.beacon_parallel_window):
348
+ if i == 0:
349
+ _input_ids, _attention_mask, _position_ids, _past_key_values, _labels = self._step()
350
+ else:
351
+ _input_ids, _attention_mask, _position_ids, _past_key_values, _labels = self._step(ignore_memory=True)
352
+
353
+ input_ids_list.append(_input_ids)
354
+ attention_mask_list.append(_attention_mask)
355
+ position_ids_list.append(_position_ids)
356
+ labels_list.append(_labels)
357
+ beacon_size_list.append(_past_key_values[0][2])
358
+ beacon_indices_list.append(_past_key_values[0][3])
359
+
360
+ if i == 0:
361
+ past_key_values = _past_key_values
362
+ if past_key_values[0][0] is None:
363
+ mem_size = 0
364
+ else:
365
+ mem_size = past_key_values[0][0].shape[self.k_seq_dim]
366
+
367
+ else:
368
+ # no memory
369
+ assert _past_key_values[0][0] is None
370
+
371
+ batch_size = self.all_input_ids.shape[0]
372
+ # NOTE: we do not need to repliace beacon tokens for the last window
373
+ seq_len = sum(x.shape[1] for x in input_ids_list) + sum(beacon_size_list) - beacon_size_list[-1]
374
+
375
+ input_ids = _input_ids.new_zeros((batch_size, seq_len)) + self.beacon_token
376
+ # all 0
377
+ attention_mask = _attention_mask.new_zeros((batch_size, 1, seq_len, mem_size + seq_len)) + self.min_value
378
+ position_ids = torch.arange(mem_size + seq_len, device=self._device).expand(batch_size, mem_size + seq_len)
379
+ # 2 indicates the beacon token is used for replication
380
+ beacon_indices = beacon_indices_list[0].new_zeros(seq_len) + 2
381
+ if _labels is not None:
382
+ # -100 because no loss on beacon tokens
383
+ labels = _labels.new_zeros((batch_size, seq_len)) - 100
384
+ else:
385
+ labels = None
386
+
387
+ start_idx = 0
388
+ position_offset = mem_size
389
+ for i in range(self.config.beacon_parallel_window):
390
+ beacon_size = beacon_size_list[i]
391
+
392
+ # populate input_ids
393
+ _input_ids = input_ids_list[i]
394
+ cur_seq_len = _input_ids.shape[1]
395
+ input_ids[:, start_idx: start_idx + cur_seq_len] = _input_ids
396
+
397
+ # populate attention_mask and position_ids
398
+ _attention_mask = attention_mask_list[i]
399
+ _position_ids = position_ids_list[i]
400
+ # the attention mask in the first window contains the mask for memory, which is redundant here
401
+ if i == 0:
402
+ _attention_mask = _attention_mask[:, :, :, mem_size:]
403
+ _position_ids = _position_ids[:, mem_size:] - mem_size
404
+
405
+ attention_mask[:, :, start_idx: start_idx + cur_seq_len, mem_size + start_idx: mem_size + start_idx + cur_seq_len] = _attention_mask
406
+ position_ids[:, mem_size + start_idx: mem_size + start_idx + cur_seq_len] = _position_ids + position_offset
407
+
408
+ # populate beacon_indices
409
+ _beacon_indices = beacon_indices_list[i]
410
+ beacon_indices[start_idx: start_idx + cur_seq_len] = _beacon_indices
411
+
412
+ # populate labels
413
+ if labels is not None:
414
+ # populate labels
415
+ _labels = labels_list[i]
416
+ labels[:, start_idx: start_idx + cur_seq_len] = _labels
417
+
418
+ # NOTE: when there is sink activations, we need to bias the position_ids for the first window
419
+ if i == 0 and self.config.beacon_sink_size > 0 and self.sink_activations[0][0] is None:
420
+ position_offset += 1
421
+
422
+ # modify the attention and position for replicated beacon tokens
423
+ if i != self.config.beacon_parallel_window - 1:
424
+ replicate_beacon_row_start = start_idx + cur_seq_len
425
+ replicate_beacon_col_start = mem_size + start_idx + cur_seq_len
426
+ # NOTE: any attention mask is okay for replicated beacon tokens, but for convenience we use the causal mask
427
+ 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)
428
+ # NOTE: all future tokens can attend to the replicated beacon tokens
429
+ attention_mask[:, :, replicate_beacon_row_start + beacon_size:, replicate_beacon_col_start: replicate_beacon_col_start + beacon_size] = 0
430
+ # NOTE: the position of replicated beacon tokens start from 0
431
+ 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:]
432
+
433
+ start_idx += cur_seq_len + beacon_size
434
+ position_offset += beacon_size
435
+
436
+ # the memory is visible to all subsequent tokens
437
+ attention_mask[:, :, :, :max(mem_size, self.config.beacon_sink_size)] = 0
438
+
439
+ # NOTE: modify beacon_indices
440
+ for i, (key, value, _, _) in enumerate(past_key_values):
441
+ past_key_values[i] = (key, value, sum(beacon_size_list), beacon_indices)
442
+
443
+ # NOTE: update _beacon_indices so that the next-token logits can be properly sliced out in self.output()
444
+ self.beacon_indices = beacon_indices
445
+
446
+ return input_ids, attention_mask, position_ids, past_key_values, labels
447
+
448
+ else:
449
+ return self._step()
450
+
451
+ def _step(self, ignore_memory=False):
452
+ """
453
+ Yield inputs for the current sliding window, including the input_ids, attention_mask, position_ids, and past_key_values.
454
+ """
455
+ #============================================#
456
+ # Check whether the inputs fulfills a window.
457
+ #============================================#
458
+
459
+ # the starting position of the current window w.r.t. the start of the current input sequence
460
+ start_idx = self.start_idx
461
+ # the end position of the current window w.r.t. the start of the current input sequence
462
+ end_idx = start_idx + self.beacon_window
463
+ # indicates if the current window is completely filled by raw activations and new tokens
464
+ # we only append beacon tokens for full windows
465
+ if end_idx > self.all_sequence_length:
466
+ # the input is shorter than the initial window size
467
+ end_idx = self.all_sequence_length
468
+ is_full_window = False
469
+ else:
470
+ is_full_window = True
471
+
472
+ # NOTE: in training, the entire sequence is input to the model at once
473
+ # In the last window, we do not need to append beacons because they will not be used at all
474
+ if self.training and end_idx == self.all_sequence_length:
475
+ next_start_idx = start_idx
476
+ is_full_window = False
477
+ raw_size_to_cache = -1
478
+ beacon_size = 0
479
+ compression_ratio = -1
480
+
481
+ # NOTE: we do not compress the beacon_skip_first tokens at the beginning of the sequence
482
+ elif self.step_idx == 0 and self.beacon_skip_first is not None:
483
+ end_idx = start_idx + self.beacon_skip_first
484
+ assert end_idx <= self.all_sequence_length
485
+ next_start_idx = end_idx
486
+ is_full_window = True
487
+ raw_size_to_cache = -1
488
+ beacon_size = 0
489
+ compression_ratio = -1
490
+
491
+ # NOTE: we do not compress tokens after beacon_skip_last tokens
492
+ elif self.beacon_skip_last is not None and start_idx >= self.beacon_skip_last:
493
+ end_idx = min(start_idx + self.beacon_window, self.all_sequence_length)
494
+ next_start_idx = end_idx
495
+ is_full_window = False
496
+ raw_size_to_cache = -1
497
+ beacon_size = 0
498
+ compression_ratio = -1
499
+
500
+ else:
501
+ #============================================#
502
+ # Set compression ratio
503
+ #============================================#
504
+ if self.config.beacon_pos == "append":
505
+ if is_full_window:
506
+ # determine compression ratio for the current window
507
+ beacon_stride = self.beacon_stride
508
+ compression_ratio = self.set_compression_ratio(start_idx=start_idx, end_idx=end_idx)
509
+
510
+ if compression_ratio > 0:
511
+ # the stride must be evenly divisible by compression_ratio
512
+ beacon_size = beacon_stride // compression_ratio
513
+ else:
514
+ # the raw activations are used as beacon activations
515
+ beacon_size = -1
516
+
517
+ # forward start_idx and end_idx
518
+ next_start_idx = start_idx + beacon_stride
519
+ # how many raw activations to save
520
+ raw_size_to_cache = end_idx - next_start_idx
521
+ else:
522
+ # no stride because the sequence has finished
523
+ next_start_idx = start_idx
524
+ # cache all raw activations
525
+ raw_size_to_cache = -1
526
+ beacon_size = 0
527
+ compression_ratio = 0
528
+
529
+ elif self.config.beacon_pos == "interleave":
530
+ # the number of raw tokens in the input_ids
531
+ input_size = end_idx - self.end_idx
532
+ # set compression ratio once the previous window has finished, otherwise, reuse the interleave_compression_ratio if the input belongs to an unfinished window
533
+ if self.is_full_window:
534
+ compression_ratio = self.set_compression_ratio(start_idx=start_idx, end_idx=end_idx)
535
+ self.interleave_compression_ratio = compression_ratio
536
+ else:
537
+ compression_ratio = self.interleave_compression_ratio
538
+
539
+ # the beacon size is non-zero even if the window is not full
540
+ if compression_ratio > 0:
541
+ # this number of beacon tokens will be inserted among the raw tokens
542
+ beacon_size = (input_size + self.interleave_remainder) // compression_ratio
543
+ else:
544
+ # the raw activations are used as beacon activations
545
+ beacon_size = -1
546
+
547
+ if is_full_window:
548
+ # move forward one window
549
+ next_start_idx = start_idx + self.beacon_stride
550
+ # no save raw activations
551
+ raw_size_to_cache = 0
552
+ else:
553
+ # no stride because the sequence has not finished
554
+ next_start_idx = start_idx
555
+ # cache all recent raw activations to be used in the next window
556
+ raw_size_to_cache = -1
557
+
558
+ #============================================#
559
+ # Slice out input_ids (raw tokens in the current window)
560
+ #============================================#
561
+ input_ids = self.all_input_ids[:, self.end_idx: end_idx].to(self._device)
562
+ attention_mask = self.all_attention_mask[:, self.end_idx: end_idx].to(self._device)
563
+ if self.all_labels is not None:
564
+ labels = self.all_labels[:, self.end_idx: end_idx].to(self._device)
565
+ else:
566
+ labels = None
567
+ batch_size = input_ids.shape[0]
568
+
569
+ #============================================#
570
+ # Insert beacon tokens if necessary.
571
+ #============================================#
572
+ # t1 = time.time()
573
+
574
+ if self.config.beacon_pos == "append":
575
+ # append beacons if necessary
576
+ if is_full_window and beacon_size > 0:
577
+ input_ids = torch.cat([input_ids, input_ids.new_full((batch_size, beacon_size), self.beacon_token)], dim=1)
578
+ # NOTE: prepend 1 to attention_mask because we have past_key_values
579
+ attention_mask = torch.cat([attention_mask, attention_mask.new_ones(batch_size, beacon_size)], dim=1)
580
+ if labels is not None:
581
+ labels = torch.cat([labels, labels.new_zeros(batch_size, beacon_size) - 100], dim=1)
582
+
583
+ elif self.config.beacon_pos == "interleave":
584
+ input_len = input_ids.shape[1]
585
+ if beacon_size > 0:
586
+ # insert beacon tokens in between raw tokens
587
+ input_ids_with_beacons = input_ids.new_full((input_ids.shape[0], input_len + beacon_size), self.beacon_token)
588
+ raw_token_indices = torch.arange(input_ids_with_beacons.shape[1], device=input_ids.device)
589
+ interleave_start_idx = compression_ratio - self.interleave_remainder
590
+ raw_token_indices = raw_token_indices[raw_token_indices % (compression_ratio + 1) != interleave_start_idx].unsqueeze(0).expand_as(input_ids)
591
+ input_ids_with_beacons = input_ids_with_beacons.scatter(dim=1, index=raw_token_indices, src=input_ids)
592
+ input_ids = input_ids_with_beacons
593
+ # attention mask
594
+ attention_mask_with_beacons = attention_mask.new_full((attention_mask.shape[0], attention_mask.shape[1] + beacon_size), 1)
595
+ attention_mask_with_beacons = attention_mask_with_beacons.scatter(dim=1, index=raw_token_indices, src=attention_mask)
596
+ attention_mask = attention_mask_with_beacons
597
+ # labels
598
+ if labels is not None:
599
+ labels_with_beacons = labels.new_full((labels.shape[0], labels.shape[1] + beacon_size), -100)
600
+ labels_with_beacons = labels_with_beacons.scatter(dim=1, index=raw_token_indices, src=labels)
601
+ labels = labels_with_beacons
602
+
603
+ if compression_ratio > 0:
604
+ # update the reminder
605
+ self.interleave_remainder = (input_len + self.interleave_remainder) % compression_ratio
606
+
607
+ # NOTE: skip computing loss in the very first window because the beacon tokens will be used in the next window
608
+ if self.training and self.step_idx == 0 and not (self.config.beacon_pos == 'interleave' and self.config.beacon_attn == 'full-coverage'):
609
+ labels[:] = -100
610
+
611
+ # t2 = time.time()
612
+
613
+ #============================================#
614
+ # Prepare beacon_indices for interleave beacon_pos, a boolean mask where True indicates the beacon tokens.
615
+ # The mask is applied on the inputs of the entire window, including the cached activations and the input_ids.
616
+ #============================================#
617
+ beacon_indices = (input_ids[0] == self.beacon_token).long()
618
+ if self.is_full_window:
619
+ self.beacon_indices = torch.tensor([], dtype=torch.long, device=input_ids.device)
620
+ # the beacon_indices always tracks the beacon tokens in both the cached activations and the input_ids
621
+ beacon_indices = torch.cat([self.beacon_indices, beacon_indices])
622
+ # record the beacon_indices for the next window
623
+ self.beacon_indices = beacon_indices
624
+ if is_full_window and beacon_size == -1:
625
+ # NOTE: the first beacon_stride raw tokens serve as beacon tokens
626
+ # we use -1 to indicate these raw tokens, so that the attention mask and position ids will not be modified
627
+ beacon_indices[:self.beacon_stride] = -1
628
+
629
+ # t3 = time.time()
630
+
631
+ #============================================#
632
+ # Prepare past_key_values.
633
+ # beacon_size: how many beacon tokens are there in the input_ids
634
+ # 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)
635
+ #============================================#
636
+ past_key_values = []
637
+ for layer_idx in range(self.config.num_hidden_layers):
638
+ if ignore_memory:
639
+ key, value = None, None
640
+ else:
641
+ sink_key, sink_value = self.sink_activations[layer_idx]
642
+ beacon_key, beacon_value = self.beacon_activations[layer_idx]
643
+ raw_key, raw_value = self.raw_activations[layer_idx]
644
+
645
+ key = cat_tensor([
646
+ sink_key, beacon_key, raw_key,
647
+ ], dim=self.k_seq_dim)
648
+ value = cat_tensor([
649
+ sink_value, beacon_value, raw_value,
650
+ ], dim=self.v_seq_dim)
651
+
652
+ layer_past_key_values = (key, value, beacon_size, beacon_indices)
653
+ past_key_values.append(layer_past_key_values)
654
+
655
+ # t4 = time.time()
656
+
657
+ #============================================#
658
+ # Prepare attention_mask and position_ids.
659
+ #============================================#
660
+ first_key = past_key_values[0][0]
661
+ mem_size = first_key.shape[self.k_seq_dim] if first_key is not None else 0
662
+ if mem_size > 0:
663
+ attention_mask = torch.cat([attention_mask.new_ones(batch_size, mem_size), attention_mask], dim=1)
664
+
665
+ input_length = input_ids.shape[1]
666
+ position_ids = torch.arange(attention_mask.shape[-1], dtype=torch.long, device=self._device).repeat(batch_size, 1)
667
+
668
+ if self.config._attn_implementation == "flash_attention_2":
669
+ 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}."
670
+ if 0 in attention_mask:
671
+ pass
672
+ else:
673
+ attention_mask = None
674
+ elif self.config._attn_implementation == "sdpa" and self.config.beacon_pos == "append" and beacon_size <= 0 and (input_length == 1 or mem_size == 0):
675
+ attention_mask = None
676
+ else:
677
+ attention_mask, position_ids = self._make_4d_attention_mask_and_position_ids(
678
+ attention_mask,
679
+ position_ids,
680
+ mem_size,
681
+ beacon_size,
682
+ compression_ratio,
683
+ )
684
+
685
+ # t5 = time.time()
686
+
687
+ # print(f"prepare inputs {t2-t1}, prepare indices {t3-t2}, prepare memory {t4-t3}, prepare attention mask {t5-t4}")
688
+
689
+ #============================================#
690
+ # Update necessary attributes.
691
+ #============================================#
692
+ # keep track of whether the current inputs is a full_window
693
+ self.is_full_window = is_full_window
694
+ # keep track of the raw_size_to_cache
695
+ self.raw_size_to_cache = raw_size_to_cache
696
+ # involked in self.output()
697
+ self.all_beacon_sizes.append(beacon_size)
698
+ # update start_idx and end_idx
699
+ # NOTE: the update of start_idx will influence self.beacon_window and self.beacon_stride in case self.beacon_skip_last is not None
700
+ # Therefore, we must make sure all calls to self.beacon_window and self.beacon_stride happen before the update of start_idx
701
+ self.start_idx = next_start_idx
702
+ self.end_idx = end_idx
703
+ self.step_idx += 1
704
+
705
+ # print(f"start_idx: {start_idx}")
706
+ # print(f"next_start_idx: {next_start_idx}")
707
+ # print(f"beacon_size: {beacon_size}")
708
+ # print(f"raw_size_to_cache: {raw_size_to_cache}")
709
+ # print(f"interleave_remainder:{self.interleave_remainder}")
710
+ # print(f"input_ids: {input_ids}")
711
+ # print(f"input_len: {input_len}")
712
+ # print(f"beacon_indices: {beacon_indices}")
713
+ # print(f"position_ids: {position_ids}")
714
+ # print(f"attention_mask:\n{attention_mask == 0}")
715
+ # x = input()
716
+ # if x == "s":
717
+ # return
718
+
719
+ return input_ids, attention_mask, position_ids, past_key_values, labels
720
+
721
+ def update_memory(self, past_key_values):
722
+ """
723
+ Accumulate beacon activations and raw activations.
724
+ """
725
+ for layer_idx, (key, value, beacon_size, beacon_indices) in enumerate(past_key_values):
726
+ # NOTE: the past_key_values are incrementally returned (only the new keys and values are returned)
727
+ previous_raw_key, previous_raw_value = self.raw_activations[layer_idx]
728
+
729
+ if self.beacon_skip_first is not None and self.sink_activations[layer_idx][0] is None:
730
+ assert key.shape[self.k_seq_dim] == self.beacon_skip_first
731
+ assert value.shape[self.k_seq_dim] == self.beacon_skip_first
732
+ self.sink_activations[layer_idx] = [
733
+ key,
734
+ value,
735
+ ]
736
+ # NOTE: no need to update raw activations and beacon activations as all activations are kept as sink activations
737
+ continue
738
+
739
+ if self.beacon_activations[layer_idx][0] is None and self.config.beacon_sink_size > 0:
740
+ # save the sink activations
741
+ # 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
742
+ self.sink_activations[layer_idx] = [
743
+ slice_tensor(key, end=self.config.beacon_sink_size, dim=self.k_seq_dim),
744
+ slice_tensor(value, end=self.config.beacon_sink_size, dim=self.v_seq_dim),
745
+ ]
746
+
747
+ if not self.is_full_window:
748
+ # this means the current input does not fulfill a window
749
+ # thus, the key and value are all raw activations, and we accumulate them until the window is fulfilled
750
+ assert self.raw_size_to_cache == -1
751
+ raw_key = cat_tensor([
752
+ previous_raw_key,
753
+ key
754
+ ], dim=self.k_seq_dim)
755
+ raw_value = cat_tensor([
756
+ previous_raw_value,
757
+ value
758
+ ], dim=self.v_seq_dim)
759
+ self.raw_activations[layer_idx] = (raw_key, raw_value)
760
+
761
+ else:
762
+ # NOTE: use the correct previous_beacon_key and value!
763
+ previous_beacon_key, previous_beacon_value = self.beacon_activations[layer_idx]
764
+
765
+ beacon_key, beacon_value, raw_key, raw_value = self._extract_beacon_and_raw_memory(
766
+ key,
767
+ value,
768
+ previous_beacon_key,
769
+ previous_beacon_value,
770
+ previous_raw_key,
771
+ previous_raw_value,
772
+ beacon_indices,
773
+ )
774
+
775
+ self.beacon_activations[layer_idx] = (beacon_key, beacon_value)
776
+ self.raw_activations[layer_idx] = (raw_key, raw_value)
777
+
778
+ def update_loss(self, batch_loss, valid_token_num):
779
+ """
780
+ Accumulate loss for later perplexity computation and backward pass.
781
+ """
782
+ if self.batch_loss is None:
783
+ # NOTE: multiply valid_token_num because batch_loss is divided by it in advance
784
+ self.batch_loss = batch_loss * valid_token_num
785
+ self.valid_token_num = valid_token_num
786
+ else:
787
+ # NOTE: avoid in-place operations, otherwise there will be gradient errors in training
788
+ self.batch_loss = self.batch_loss + batch_loss * valid_token_num
789
+ self.valid_token_num = self.valid_token_num + valid_token_num
790
+
791
+ def output(self, model_outputs):
792
+ """
793
+ Override loss with accumulated loss. Update the next-token logits.
794
+ """
795
+ # override loss
796
+ if self.batch_loss is not None:
797
+ # here the batch_loss is the summation of all token losses in each element
798
+ loss = self.batch_loss.sum() / self.valid_token_num.sum()
799
+
800
+ # NOTE: prevent nan
801
+ batch_loss = self.batch_loss / self.valid_token_num
802
+ if (self.valid_token_num == 0).any():
803
+ batch_loss = batch_loss.masked_fill(self.valid_token_num == 0, 0.)
804
+
805
+ # NOTE: we must use dict to override values, otherwise trainer cannot find loss
806
+ model_outputs["loss"] = loss
807
+ model_outputs["batch_loss"] = batch_loss
808
+
809
+ # override last_hidden_states (used in generation)
810
+ beacon_size = self.all_beacon_sizes[-1]
811
+ # remove logits corresponding to beacon tokens
812
+ if beacon_size > 0:
813
+ logits = model_outputs["logits"]
814
+ beacon_indices = self.beacon_indices[-logits.shape[1]:]
815
+ model_outputs["logits"] = logits[:, beacon_indices == 0]
816
+
817
+ return model_outputs
818
+
819
+ def _make_4d_attention_mask_and_position_ids(
820
+ self,
821
+ attention_mask,
822
+ position_ids,
823
+ mem_size,
824
+ beacon_size,
825
+ compression_ratio,
826
+ ):
827
+ """
828
+ Convert attention_mask into causal 4D attention_mask (batch_size, head_num, query_len, key_len).
829
+ """
830
+ tgt_size = attention_mask.size(-1) - mem_size
831
+ dtype = self.dtype
832
+ min_value = self.min_value
833
+ device = self._device
834
+ batch_size, src_size = attention_mask.size()
835
+
836
+ # square for memory, and lower triangular for input_ids
837
+ causal_mask = torch.full((tgt_size, tgt_size), min_value, device=device, dtype=dtype)
838
+ mask_cond = torch.arange(causal_mask.size(-1), device=device)
839
+ causal_mask.masked_fill_(mask_cond < (mask_cond + 1).view(causal_mask.size(-1), -1), 0)
840
+ causal_mask = torch.cat([torch.zeros(tgt_size, mem_size, dtype=dtype, device=device), causal_mask], dim=-1)
841
+ causal_mask = causal_mask[None, None, ...].expand(batch_size, 1, tgt_size, src_size)
842
+ # 1 for non-padding tokens
843
+ expand_mask = attention_mask[:, None, None, :].expand(batch_size, 1, tgt_size, src_size)
844
+ invert_mask = 1.0 - expand_mask
845
+ invert_mask.masked_fill_(invert_mask.bool(), min_value)
846
+
847
+ attention_mask = causal_mask.masked_fill(invert_mask.bool(), min_value)
848
+
849
+ if self.config.beacon_attn == "step-expansion":
850
+ # each beacon can attend to one more sub-interval than its predecessor
851
+
852
+ if self.config.beacon_pos == "append" and beacon_size > 0:
853
+ window_size = self.beacon_window
854
+ window_size_with_beacon = window_size + beacon_size
855
+ beacon_start_idx = -beacon_size
856
+ # batch_size, head_num, window_size
857
+ reference_attention_mask = attention_mask[..., -beacon_size - 1, -window_size_with_beacon: -beacon_size]
858
+
859
+ # compression_ratio, 2 * compression_ratio, ..., beacon_size * compression_ratio
860
+ beacon_arange = torch.arange(1, beacon_size + 1, device=device) * compression_ratio
861
+ # 0, 1, 2, ..., window_size - 1
862
+ ordinal_arange = torch.arange(window_size, device=device)
863
+ # beacon_size, window_size
864
+ valid_pos = ordinal_arange.expand(beacon_size, window_size) < beacon_arange.unsqueeze(-1)
865
+ # beacon_size, window_size
866
+ ordinal_attention_mask = torch.where(valid_pos, 0, min_value)
867
+ # NOTE: add reference attention_mask so that padding tokens are considered
868
+ ordinal_attention_mask = ordinal_attention_mask[None, None, ...] + reference_attention_mask.unsqueeze(-2)
869
+
870
+ if self.config.beacon_attend_prev:
871
+ beacon_attention_mask = attention_mask.new_full((beacon_size, beacon_size), min_value).triu(1)
872
+ # the beacon token is next to the last ordinal token it attends to
873
+ ordinal_position_ids = position_ids[:, -window_size_with_beacon: -beacon_size]
874
+ beacon_position_ids = ordinal_position_ids[:, compression_ratio - 1::compression_ratio] + torch.arange(1, beacon_size + 1, device=device)[None]
875
+ position_ids[:, beacon_start_idx:] = beacon_position_ids
876
+ else:
877
+ beacon_attention_mask = attention_mask.new_full((beacon_size, beacon_size), min_value).fill_diagonal_(0)
878
+ # the beacon token is next to the last ordinal token it attends to
879
+ ordinal_position_ids = position_ids[:, -window_size_with_beacon: -beacon_size]
880
+ beacon_position_ids = ordinal_position_ids[:, compression_ratio - 1::compression_ratio] + 1
881
+ position_ids[:, beacon_start_idx:] = beacon_position_ids
882
+
883
+ attention_mask[..., beacon_start_idx:, -window_size_with_beacon: -beacon_size] = ordinal_attention_mask
884
+ attention_mask[..., beacon_start_idx:, beacon_start_idx:] = beacon_attention_mask
885
+
886
+ # NOTE: the attention mask should be modified when there is beacon token within the window, not in the input_ids
887
+ elif self.config.beacon_pos == "interleave" and (self.beacon_indices == 1).any():
888
+ assert self.config.beacon_attend_prev == False, f"Make sure beacon_attend_prev is False if using 'interleave' beacon pos!"
889
+
890
+ beacon_indices = self.beacon_indices
891
+
892
+ cur_position_ids = position_ids[:, -len(beacon_indices):]
893
+ base_position = cur_position_ids[:, 0] - 1
894
+ # NOTE: alternate position so that the position of raw tokens are consistent
895
+ position_template = cur_position_ids.new_ones(cur_position_ids.shape)
896
+ position_template[:, compression_ratio + 1::compression_ratio + 1] = 0
897
+ cur_position_ids = base_position + position_template.cumsum(-1)
898
+ position_ids[:, -len(beacon_indices):] = cur_position_ids
899
+
900
+ cur_input_length = len(beacon_indices)
901
+ cur_attention_mask = attention_mask[..., -cur_input_length:, -cur_input_length:]
902
+ # mask all beacon columns
903
+ cur_attention_mask[..., beacon_indices] = min_value
904
+ # beacon tokens can attend to themselves
905
+ input_ids_attention_mask = cur_attention_mask[..., -tgt_size:, -tgt_size:]
906
+ input_ids_attention_mask[..., range(tgt_size), range(tgt_size)] = 0
907
+
908
+ elif self.config.beacon_attn == "segmentation":
909
+ # each beacon can attend to its corresponding sub-interval
910
+
911
+ if self.config.beacon_pos == "append" and beacon_size > 0:
912
+ window_size = self.beacon_window
913
+ window_size_with_beacon = window_size + beacon_size
914
+ beacon_start_idx = -beacon_size
915
+ # batch_size, head_num, window_size
916
+ reference_attention_mask = attention_mask[..., -beacon_size - 1, -window_size_with_beacon: -beacon_size]
917
+
918
+ # beacon_size, compression_ratio
919
+ indices = torch.arange(compression_ratio * beacon_size, device=device).view(beacon_size, -1)
920
+ # beacon_size, window_size
921
+ ordinal_attention_mask = attention_mask.new_full((beacon_size, window_size), min_value)
922
+ ordinal_attention_mask.scatter_(dim=-1, index=indices, value=0)
923
+
924
+ # NOTE: add reference attention_mask so that padding tokens are considered
925
+ ordinal_attention_mask = ordinal_attention_mask[None, None, ...] + reference_attention_mask.unsqueeze(-2)
926
+
927
+ if self.config.beacon_attend_prev:
928
+ beacon_attention_mask = attention_mask.new_full((beacon_size, beacon_size), min_value).triu(1)
929
+ # the beacon token is next to the last ordinal token it attends to
930
+ beacon_position_ids = position_ids.new_full(beacon_size, fill_value=compression_ratio + mem_size)
931
+ beacon_position_ids = beacon_position_ids + torch.arange(beacon_size)
932
+ position_ids[:, beacon_start_idx:] = beacon_position_ids
933
+ else:
934
+ beacon_attention_mask = attention_mask.new_full((beacon_size, beacon_size), min_value).fill_diagonal_(0)
935
+ # the beacon token is next to the last ordinal token it attends to
936
+ beacon_position_ids = position_ids.new_full(beacon_size, fill_value=compression_ratio + mem_size)
937
+ position_ids[:, beacon_start_idx:] = beacon_position_ids
938
+
939
+ attention_mask[..., beacon_start_idx:, -window_size_with_beacon: -beacon_size] = ordinal_attention_mask
940
+ attention_mask[..., beacon_start_idx:, beacon_start_idx:] = beacon_attention_mask
941
+ # beacons of different ratios are blind to others
942
+ attention_mask[..., beacon_start_idx:, -beacon_size: beacon_start_idx] = min_value
943
+
944
+ elif self.config.beacon_pos == "interleave":
945
+ raise NotImplementedError
946
+
947
+ elif self.config.beacon_attn == "full-coverage":
948
+ pass
949
+
950
+ return attention_mask, position_ids
951
+
952
+ def _extract_beacon_and_raw_memory(
953
+ self,
954
+ key,
955
+ value,
956
+ previous_beacon_key,
957
+ previous_beacon_value,
958
+ previous_raw_key,
959
+ previous_raw_value,
960
+ beacon_indices,
961
+ ):
962
+ """Extract beacon and raw memory from the returned key and value when the window is full."""
963
+ key = cat_tensor([
964
+ previous_raw_key,
965
+ key
966
+ ], dim=self.k_seq_dim)
967
+ value = cat_tensor([
968
+ previous_raw_value,
969
+ value
970
+ ], dim=self.v_seq_dim)
971
+
972
+ # NOTE: we use magic slice instead of boolean index here for efficiency
973
+ beacon_key = slice_tensor(key, index=torch.logical_or(beacon_indices == 1, beacon_indices == -1), dim=self.k_seq_dim)
974
+ beacon_value = slice_tensor(value, index=torch.logical_or(beacon_indices == 1, beacon_indices == -1), dim=self.v_seq_dim)
975
+
976
+ if self.config.beacon_accum:
977
+ beacon_key = cat_tensor([previous_beacon_key, beacon_key], dim=self.k_seq_dim)
978
+ beacon_value = cat_tensor([previous_beacon_value, beacon_value], dim=self.v_seq_dim)
979
+
980
+ if self.raw_size_to_cache > 0:
981
+ raw_key = slice_tensor(key, index=beacon_indices == 0, dim=self.k_seq_dim)
982
+ raw_key = slice_tensor(raw_key, start=-raw_size_to_cache, dim=self.k_seq_dim)
983
+
984
+ raw_value = slice_tensor(value, index=beacon_indices == 0, dim=self.v_seq_dim)
985
+ raw_value = slice_tensor(raw_value, start=-raw_size_to_cache, dim=self.v_seq_dim)
986
+
987
+ else:
988
+ raw_key = None
989
+ raw_value = None
990
+
991
+ return beacon_key, beacon_value, raw_key, raw_value
992
+
993
+
994
+ def slice_tensor(x, start=None, end=None, step=None, index=None, dim=2):
995
+ if x is None:
996
+ return None
997
+ if end == 0:
998
+ return None
999
+ if start == x.shape[dim]:
1000
+ return None
1001
+ if start is not None and start == end:
1002
+ return None
1003
+ if dim == 2:
1004
+ if index is not None:
1005
+ return x[:, :, index]
1006
+ elif start is None and end is not None:
1007
+ if step is None:
1008
+ return x[:, :, :end, ...]
1009
+ else:
1010
+ return x[:, :, :end:step, ...]
1011
+ elif start is not None and end is None:
1012
+ if step is None:
1013
+ return x[:, :, start:, ...]
1014
+ else:
1015
+ return x[:, :, start::step, ...]
1016
+ elif start is not None and end is not None:
1017
+ if step is None:
1018
+ return x[:, :, start:end, ...]
1019
+ else:
1020
+ return x[:, :, start:end:step, ...]
1021
+ elif dim == 1:
1022
+ if index is not None:
1023
+ return x[:, :, index]
1024
+ elif start is None and end is not None:
1025
+ if step is None:
1026
+ return x[:, :end, ...]
1027
+ else:
1028
+ return x[:, :end:step, ...]
1029
+ elif start is not None and end is None:
1030
+ if step is None:
1031
+ return x[:, start:, ...]
1032
+ else:
1033
+ return x[:, start::step, ...]
1034
+ elif start is not None and end is not None:
1035
+ if step is None:
1036
+ return x[:, start:end, ...]
1037
+ else:
1038
+ return x[:, start:end:step, ...]
1039
+ else:
1040
+ raise NotImplementedError
1041
+
1042
+ def cat_tensor(list_of_tensors, dim=-1):
1043
+ list_of_tensors = [t for t in list_of_tensors if t is not None]
1044
+ if len(list_of_tensors) > 1:
1045
+ result = torch.cat(list_of_tensors, dim=dim)
1046
+ elif len(list_of_tensors) == 1:
1047
+ result = list_of_tensors[0]
1048
+ else:
1049
+ result = None
1050
+ return result
1051
+
1052
+ def slice_activations(activations, start=None, end=None, k_seq_dim=2, v_seq_dim=2):
1053
+ new_activations = []
1054
+ for key, value in activations:
1055
+ new_key = slice_tensor(key, start=start, end=end, dim=k_seq_dim)
1056
+ new_value = slice_tensor(value, start=start, end=end, dim=v_seq_dim)
1057
+ new_activations.append([new_key, new_value])
1058
+ return new_activations
1059
+
1060
+ def cat_activations(list_of_activations, k_seq_dim=2, v_seq_dim=2):
1061
+ 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]}."
1062
+
1063
+ new_activations = []
1064
+ for layer_idx in range(len(list_of_activations[0])):
1065
+ keys = [x[layer_idx][0] for x in list_of_activations]
1066
+ values = [x[layer_idx][1] for x in list_of_activations]
1067
+
1068
+ new_key = cat_tensor(keys, dim=k_seq_dim)
1069
+ new_value = cat_tensor(values, dim=v_seq_dim)
1070
+ new_activations.append([new_key, new_value])
1071
+ return new_activations
1072
+
1073
+ def interleave_activations(main_activations, augment_activations, main_spans, augment_spans, k_seq_dim=2, v_seq_dim=2, device=torch.device("cuda")):
1074
+ """ Interleave main_activations and augment_activations according to main_span and augment_span.
1075
+
1076
+ Args:
1077
+ 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.
1078
+ augment_span: a list of tuples (start_idx, end_idx)
1079
+ """
1080
+ 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)}!"
1081
+ 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!"
1082
+
1083
+ new_activations = []
1084
+ for layer_idx in range(len(main_activations)):
1085
+ main_key, main_value = main_activations[layer_idx]
1086
+ augment_key, augment_value = augment_activations[layer_idx]
1087
+
1088
+ sliced_keys = []
1089
+ sliced_values = []
1090
+
1091
+ augment_idx = 0
1092
+ for start, end in main_spans:
1093
+ if start is None and end is None:
1094
+ # this means the augment key/value should be plugged in
1095
+ augment_start, augment_end = augment_spans[augment_idx]
1096
+ sliced_key = slice_tensor(
1097
+ augment_key,
1098
+ start=augment_start,
1099
+ end=augment_end,
1100
+ dim=k_seq_dim
1101
+ ).to(device)
1102
+ sliced_value = slice_tensor(
1103
+ augment_value,
1104
+ start=augment_start,
1105
+ end=augment_end,
1106
+ dim=v_seq_dim
1107
+ ).to(device)
1108
+
1109
+ else:
1110
+ sliced_key = slice_tensor(
1111
+ main_key,
1112
+ start=start,
1113
+ end=end,
1114
+ dim=k_seq_dim
1115
+ )
1116
+ sliced_value = slice_tensor(
1117
+ main_value,
1118
+ start=start,
1119
+ end=end,
1120
+ dim=v_seq_dim
1121
+ )
1122
+
1123
+ sliced_keys.append(sliced_key)
1124
+ sliced_values.append(sliced_value)
1125
+
1126
+ new_key = cat_tensor(sliced_keys, dim=k_seq_dim)
1127
+ new_value = cat_tensor(sliced_values, dim=v_seq_dim)
1128
+ new_activations.append([new_key, new_value])
1129
+
1130
+ return new_activations
1131
+
1132
+ def softmax(x:np.ndarray, axis=-1, temperature=1):
1133
+ if isinstance(x, list):
1134
+ x = np.array(x)
1135
+ x = x / temperature
1136
+ x = x - x.max(axis=axis, keepdims=True)
1137
+ y = np.exp(x)
1138
+ return y / y.sum(axis=axis, keepdims=True)
1139
+
1140
+ def l1_norm(x):
1141
+ sum_x = sum(x)
1142
+ x = [y/sum_x for y in x]
1143
+ return x
modeling_qwen2.py ADDED
@@ -0,0 +1,1309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
34
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
35
+ from transformers.modeling_utils import PreTrainedModel
36
+ from transformers.utils import (
37
+ add_start_docstrings,
38
+ add_start_docstrings_to_model_forward,
39
+ is_flash_attn_2_available,
40
+ is_flash_attn_greater_or_equal_2_10,
41
+ logging,
42
+ replace_return_docstrings,
43
+ )
44
+ from transformers.integrations import is_deepspeed_zero3_enabled
45
+ from .configuration_qwen2 import Qwen2Config
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 .modeling_beacon import Memory
55
+ from .modeling_utils import optional_grad_ctx, compute_loss, get_rope, ModelOutput
56
+
57
+
58
+ logger = logging.get_logger(__name__)
59
+
60
+
61
+ _CHECKPOINT_FOR_DOC = "Qwen/Qwen2-7B-beta"
62
+ _CONFIG_FOR_DOC = "Qwen2Config"
63
+
64
+ QWEN2_PRETRAINED_MODEL_ARCHIVE_LIST = [
65
+ "Qwen/Qwen2-7B-beta",
66
+ # See all Qwen2 models at https://huggingface.co/models?filter=qwen2
67
+ ]
68
+
69
+
70
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
71
+ def _get_unpad_data(attention_mask):
72
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
73
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
74
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
75
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
76
+ return (
77
+ indices,
78
+ cu_seqlens,
79
+ max_seqlen_in_batch,
80
+ )
81
+
82
+
83
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Qwen2
84
+ class Qwen2RMSNorm(nn.Module):
85
+ def __init__(self, hidden_size, eps=1e-6):
86
+ """
87
+ Qwen2RMSNorm is equivalent to T5LayerNorm
88
+ """
89
+ super().__init__()
90
+ self.weight = nn.Parameter(torch.ones(hidden_size))
91
+ self.variance_epsilon = eps
92
+
93
+ def forward(self, hidden_states):
94
+ input_dtype = hidden_states.dtype
95
+ hidden_states = hidden_states.to(torch.float32)
96
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
97
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
98
+ return self.weight * hidden_states.to(input_dtype)
99
+
100
+
101
+ # Copied from transformers.models.mistral.modeling_mistral.Qwen2MLP with Qwen2->Qwen2
102
+ class Qwen2MLP(nn.Module):
103
+ def __init__(self, config):
104
+ super().__init__()
105
+ self.config = config
106
+ self.hidden_size = config.hidden_size
107
+ self.intermediate_size = config.intermediate_size
108
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
109
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
110
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
111
+ self.act_fn = ACT2FN[config.hidden_act]
112
+
113
+ def forward(self, x):
114
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
115
+ return down_proj
116
+
117
+
118
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
119
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
120
+ """
121
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
122
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
123
+ """
124
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
125
+ if n_rep == 1:
126
+ return hidden_states
127
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
128
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
129
+
130
+
131
+ class Qwen2Attention(nn.Module):
132
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
133
+
134
+ def __init__(self, config: Qwen2Config, layer_idx: Optional[int] = None):
135
+ super().__init__()
136
+ self.config = config
137
+ self.layer_idx = layer_idx
138
+ if layer_idx is None:
139
+ logger.warning_once(
140
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
141
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
142
+ "when creating this class."
143
+ )
144
+
145
+ self.attention_dropout = config.attention_dropout
146
+ self.hidden_size = config.hidden_size
147
+ self.num_heads = config.num_attention_heads
148
+ self.head_dim = self.hidden_size // self.num_heads
149
+ self.num_key_value_heads = config.num_key_value_heads
150
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
151
+ self.max_position_embeddings = config.max_position_embeddings
152
+ self.rope_theta = config.rope_theta
153
+ self.is_causal = True
154
+
155
+ if (self.head_dim * self.num_heads) != self.hidden_size:
156
+ raise ValueError(
157
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
158
+ f" and `num_heads`: {self.num_heads})."
159
+ )
160
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
161
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
162
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
163
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
164
+
165
+ self.rotary_emb = get_rope(self.head_dim, config.rope_theta, config.max_position_embeddings, getattr(config, "rope_scaling", None))
166
+
167
+ # NOTE: add extra parameters for beacon tokens
168
+ # skip post initialization to speed up loading
169
+ if "q" in config.beacon_param:
170
+ self.beacon_q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=self.q_proj.bias is not None)
171
+ # NOTE: initialize the beacon parameters as zero
172
+ self.beacon_q_proj.weight.data.zero_()
173
+ self.beacon_q_proj._is_hf_initialized = True
174
+ if "k" in config.beacon_param:
175
+ 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)
176
+ self.beacon_k_proj.weight.data.zero_()
177
+ self.beacon_k_proj._is_hf_initialized = True
178
+ if "v" in config.beacon_param:
179
+ 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)
180
+ self.beacon_v_proj.weight.data.zero_()
181
+ self.beacon_v_proj._is_hf_initialized = True
182
+ if "o" in config.beacon_param:
183
+ self.beacon_o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=self.o_proj.bias is not None)
184
+ self.beacon_o_proj.weight.data.zero_()
185
+ self.beacon_o_proj._is_hf_initialized = True
186
+
187
+ def _init_beacon_proj(self, missing_keys):
188
+ """Initialize the beacon projection weight with that of the ordinal projection."""
189
+ beacon_param = self.config.beacon_param
190
+
191
+ if is_deepspeed_zero3_enabled():
192
+ # FIXME: after deepspeed initialization, some weights becomes non-zero
193
+ # For Mistral, there are rows that are full of zeros
194
+ # For Mistral, there are values bigger than 1e29...
195
+
196
+ import deepspeed
197
+ if "q" in beacon_param:
198
+ params = [self.beacon_q_proj.weight, self.q_proj.weight]
199
+ if self.q_proj.bias is not None:
200
+ params.extend([self.beacon_q_proj.bias, self.q_proj.bias])
201
+ with deepspeed.zero.GatheredParameters(params, modifier_rank=0):
202
+ # FIXME: after deepspeed initialization, some weights becomes non-zero, but there are rows that are full of zeros
203
+ if (self.beacon_q_proj.weight.sum(-1) == 0).any() or (self.beacon_q_proj.weight > 1e29).any():
204
+ self.beacon_q_proj.weight.data[:] = self.q_proj.weight.data
205
+ if self.q_proj.bias is not None:
206
+ self.beacon_q_proj.bias.data[:] = self.q_proj.bias.data
207
+ if "k" in beacon_param:
208
+ params = [self.beacon_k_proj.weight, self.k_proj.weight]
209
+ if self.k_proj.bias is not None:
210
+ params.extend([self.beacon_k_proj.bias, self.k_proj.bias])
211
+ with deepspeed.zero.GatheredParameters(params, modifier_rank=0):
212
+ # FIXME: after deepspeed initialization, some weights becomes non-zero, but there are rows that are full of zeros
213
+ if (self.beacon_k_proj.weight.sum(-1) == 0).any() or (self.beacon_k_proj.weight > 1e29).any():
214
+ self.beacon_k_proj.weight.data[:] = self.k_proj.weight.data
215
+ if self.k_proj.bias is not None:
216
+ self.beacon_k_proj.bias.data[:] = self.k_proj.bias.data
217
+ if "v" in beacon_param:
218
+ params = [self.beacon_v_proj.weight, self.v_proj.weight]
219
+ if self.v_proj.bias is not None:
220
+ params.extend([self.beacon_v_proj.bias, self.v_proj.bias])
221
+ with deepspeed.zero.GatheredParameters(params, modifier_rank=0):
222
+ # FIXME: after deepspeed initialization, some weights becomes non-zero, but there are rows that are full of zeros
223
+ if (self.beacon_v_proj.weight.sum(-1) == 0).any() or (self.beacon_v_proj.weight > 1e29).any():
224
+ self.beacon_v_proj.weight.data[:] = self.v_proj.weight.data
225
+ if self.v_proj.bias is not None:
226
+ self.beacon_v_proj.bias.data[:] = self.v_proj.bias.data
227
+ if "o" in beacon_param:
228
+ params = [self.beacon_o_proj.weight, self.o_proj.weight]
229
+ if self.o_proj.bias is not None:
230
+ params.extend([self.beacon_o_proj.bias, self.o_proj.bias])
231
+ with deepspeed.zero.GatheredParameters(params, modifier_rank=0):
232
+ # FIXME: after deepspeed initialization, some weights becomes non-zero, but there are rows that are full of zeros
233
+ if (self.beacon_o_proj.weight.sum(-1) == 0).any() or (self.beacon_o_proj.weight > 1e29).any():
234
+ self.beacon_o_proj.weight.data[:] = self.o_proj.weight.data
235
+ if self.o_proj.bias is not None:
236
+ self.beacon_o_proj.bias.data[:] = self.o_proj.bias.data
237
+ else:
238
+ # only copy the value in-place, without tieing the weight
239
+ if "q" in beacon_param and any("beacon_q_proj" in missing_key for missing_key in missing_keys):
240
+ # FIXME: some beacon weights are not initialized as zero for mistral model, why?
241
+ # if (self.beacon_q_proj.weight == 0).all():
242
+ self.beacon_q_proj.weight.data[:] = self.q_proj.weight.data
243
+ if self.q_proj.bias is not None:
244
+ self.beacon_q_proj.bias.data[:] = self.q_proj.bias.data
245
+ if "k" in beacon_param and any("beacon_k_proj" in missing_key for missing_key in missing_keys):
246
+ # if (self.beacon_k_proj.weight == 0).all():
247
+ self.beacon_k_proj.weight.data[:] = self.k_proj.weight.data
248
+ if self.k_proj.bias is not None:
249
+ self.beacon_k_proj.bias.data[:] = self.k_proj.bias.data
250
+ if "v" in beacon_param and any("beacon_v_proj" in missing_key for missing_key in missing_keys):
251
+ # if (self.beacon_v_proj.weight == 0).all():
252
+ self.beacon_v_proj.weight.data[:] = self.v_proj.weight.data
253
+ if self.v_proj.bias is not None:
254
+ self.beacon_v_proj.bias.data[:] = self.v_proj.bias.data
255
+ if "o" in beacon_param and any("beacon_o_proj" in missing_key for missing_key in missing_keys):
256
+ # if (self.beacon_o_proj.weight == 0).all():
257
+ self.beacon_o_proj.weight.data[:] = self.o_proj.weight.data
258
+ if self.o_proj.bias is not None:
259
+ self.beacon_o_proj.bias.data[:] = self.o_proj.bias.data
260
+
261
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
262
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
263
+
264
+ def qkv_proj_with_beacon(self, hidden_states, beacon_size, beacon_indices):
265
+ if beacon_size > 0:
266
+ # 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
267
+ cur_beacon_indices = beacon_indices[-hidden_states.shape[1]:]
268
+
269
+ # NOTE: there is slight redundant computation because ordinal tokens should never be projected by beacon matrices, but we are doing this for efficiency
270
+ if "q" in self.config.beacon_param:
271
+ ordinal_query_states = self.q_proj(hidden_states)
272
+ beacon_query_states = self.beacon_q_proj(hidden_states)
273
+ query_states = torch.where((cur_beacon_indices == 0)[:, None], ordinal_query_states, beacon_query_states)
274
+ if (cur_beacon_indices == 2).any():
275
+ # beacon_indices == 2 means the beacon token is used to replicate the ones in previous window for parallel encoding
276
+ # we should slice out all beacon tokens then copy them to the replicate beacon tokens
277
+ query_states[:, cur_beacon_indices == 2] = beacon_query_states[:, cur_beacon_indices == 1][:, :(cur_beacon_indices == 2).sum()]
278
+ else:
279
+ query_states = self.q_proj(hidden_states)
280
+
281
+ if "k" in self.config.beacon_param:
282
+ ordinal_key_states = self.k_proj(hidden_states)
283
+ beacon_key_states = self.beacon_k_proj(hidden_states)
284
+ key_states = torch.where((cur_beacon_indices == 0)[:, None], ordinal_key_states, beacon_key_states)
285
+ if (cur_beacon_indices == 2).any():
286
+ # beacon_indices == 2 means the beacon token is used to replicate the ones in previous window for parallel encoding
287
+ # we should slice out all beacon tokens then copy them to the replicate beacon tokens
288
+ key_states[:, cur_beacon_indices == 2] = beacon_key_states[:, cur_beacon_indices == 1][:, :(cur_beacon_indices == 2).sum()]
289
+ else:
290
+ key_states = self.k_proj(hidden_states)
291
+
292
+ if "v" in self.config.beacon_param:
293
+ ordinal_value_states = self.v_proj(hidden_states)
294
+ beacon_value_states = self.beacon_v_proj(hidden_states)
295
+ value_states = torch.where((cur_beacon_indices == 0)[:, None], ordinal_value_states, beacon_value_states)
296
+ if (cur_beacon_indices == 2).any():
297
+ # beacon_indices == 2 means the beacon token is used to replicate the ones in previous window for parallel encoding
298
+ # we should slice out all beacon tokens then copy them to the replicate beacon tokens
299
+ value_states[:, cur_beacon_indices == 2] = beacon_value_states[:, cur_beacon_indices == 1][:, :(cur_beacon_indices == 2).sum()]
300
+ else:
301
+ value_states = self.v_proj(hidden_states)
302
+
303
+ else:
304
+ query_states = self.q_proj(hidden_states)
305
+ key_states = self.k_proj(hidden_states)
306
+ value_states = self.v_proj(hidden_states)
307
+
308
+ return query_states, key_states, value_states
309
+
310
+ def o_proj_with_beacon(self, attn_output, beacon_size, beacon_indices):
311
+ if beacon_size > 0:
312
+ # 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
313
+ cur_beacon_indices = beacon_indices[-attn_output.shape[1]:]
314
+
315
+ if "o" in self.config.beacon_param:
316
+ ordinal_attn_output = self.o_proj(attn_output)
317
+ beacon_attn_output = self.beacon_o_proj(attn_output)
318
+ attn_output = torch.where((cur_beacon_indices == 0)[:, None], ordinal_attn_output, beacon_attn_output)
319
+ else:
320
+ attn_output = self.o_proj(attn_output)
321
+ else:
322
+ attn_output = self.o_proj(attn_output)
323
+ return attn_output
324
+
325
+ def forward(
326
+ self,
327
+ hidden_states: torch.Tensor,
328
+ attention_mask: Optional[torch.Tensor] = None,
329
+ position_ids: Optional[torch.LongTensor] = None,
330
+ past_key_value: Optional[Cache] = None,
331
+ output_attentions: bool = False,
332
+ use_cache: bool = False,
333
+ **kwargs,
334
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
335
+ if "padding_mask" in kwargs:
336
+ warnings.warn(
337
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
338
+ )
339
+
340
+ bsz, q_len, _ = hidden_states.size()
341
+ kv_seq_len = hidden_states.shape[-2]
342
+ past_key, past_value, beacon_size, beacon_indices = past_key_value
343
+
344
+ if past_key is not None:
345
+ past_seq_len = past_key.shape[2]
346
+ kv_seq_len += past_seq_len
347
+ else:
348
+ past_seq_len = 0
349
+
350
+ query_states, key_states, value_states = self.qkv_proj_with_beacon(hidden_states, beacon_size, beacon_indices)
351
+
352
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
353
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
354
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
355
+
356
+ # return keys and values before rope
357
+ # NOTE: incrementally return keys and values for efficiency
358
+ past_key_value = (key_states, value_states, beacon_size, beacon_indices)
359
+
360
+ if past_key is not None:
361
+ # reuse k, v, self_attention
362
+ key_states = torch.cat([past_key, key_states], dim=2)
363
+ value_states = torch.cat([past_value, value_states], dim=2)
364
+
365
+ query_states, key_states = self.rotary_emb(query_states, key_states, position_ids)
366
+
367
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
368
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
369
+
370
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
371
+
372
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
373
+ raise ValueError(
374
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
375
+ f" {attn_weights.size()}"
376
+ )
377
+
378
+ if attention_mask is not None:
379
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
380
+ raise ValueError(
381
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
382
+ )
383
+ attn_weights = attn_weights + attention_mask
384
+
385
+ # upcast attention to fp32
386
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
387
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
388
+ attn_output = torch.matmul(attn_weights, value_states)
389
+
390
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
391
+ raise ValueError(
392
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
393
+ f" {attn_output.size()}"
394
+ )
395
+
396
+ attn_output = attn_output.transpose(1, 2).contiguous()
397
+
398
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
399
+
400
+ attn_output = self.o_proj_with_beacon(attn_output, beacon_size, beacon_indices)
401
+
402
+ if not output_attentions:
403
+ attn_weights = None
404
+
405
+ return attn_output, attn_weights, past_key_value
406
+
407
+
408
+ class Qwen2SdpaAttention(Qwen2Attention):
409
+ """
410
+ Qwen2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
411
+ `Qwen2Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
412
+ SDPA API.
413
+ """
414
+
415
+ # Adapted from Qwen2Attention.forward
416
+ def forward(
417
+ self,
418
+ hidden_states: torch.Tensor,
419
+ attention_mask: Optional[torch.Tensor] = None,
420
+ position_ids: Optional[torch.LongTensor] = None,
421
+ past_key_value: Optional[Cache] = None,
422
+ output_attentions: bool = False,
423
+ use_cache: bool = False,
424
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
425
+ if output_attentions:
426
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
427
+ logger.warning_once(
428
+ "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, "
429
+ '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.'
430
+ )
431
+ return super().forward(
432
+ hidden_states=hidden_states,
433
+ attention_mask=attention_mask,
434
+ position_ids=position_ids,
435
+ past_key_value=past_key_value,
436
+ output_attentions=output_attentions,
437
+ use_cache=use_cache,
438
+ )
439
+ bsz, q_len, _ = hidden_states.size()
440
+ kv_seq_len = hidden_states.shape[-2]
441
+ past_key, past_value, beacon_size, beacon_indices = past_key_value
442
+ if past_key is not None:
443
+ past_seq_len = past_key.shape[2]
444
+ kv_seq_len += past_seq_len
445
+ else:
446
+ past_seq_len = 0
447
+
448
+ query_states, key_states, value_states = self.qkv_proj_with_beacon(hidden_states, beacon_size, beacon_indices)
449
+
450
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
451
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
452
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
453
+
454
+ # return keys and values before rope
455
+ # NOTE: incrementally return keys and values for efficiency
456
+ past_key_value = (key_states, value_states, beacon_size, beacon_indices)
457
+
458
+ if past_key is not None:
459
+ # reuse k, v, self_attention
460
+ key_states = torch.cat([past_key, key_states], dim=2)
461
+ value_states = torch.cat([past_value, value_states], dim=2)
462
+
463
+ query_states, key_states = self.rotary_emb(query_states, key_states, position_ids)
464
+
465
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
466
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
467
+
468
+ if attention_mask is not None:
469
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
470
+ raise ValueError(
471
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
472
+ )
473
+
474
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
475
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
476
+ if query_states.device.type == "cuda" and attention_mask is not None:
477
+ query_states = query_states.contiguous()
478
+ key_states = key_states.contiguous()
479
+ value_states = value_states.contiguous()
480
+
481
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
482
+ query_states,
483
+ key_states,
484
+ value_states,
485
+ attn_mask=attention_mask,
486
+ dropout_p=self.attention_dropout if self.training else 0.0,
487
+ # 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.
488
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
489
+ )
490
+
491
+ attn_output = attn_output.transpose(1, 2).contiguous()
492
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
493
+ attn_output = self.o_proj_with_beacon(attn_output, beacon_size, beacon_indices)
494
+
495
+ return attn_output, None, past_key_value
496
+
497
+
498
+ class Qwen2FlashAttention2(Qwen2Attention):
499
+ """
500
+ Qwen2 flash attention module. This module inherits from `Qwen2Attention` as the weights of the module stays
501
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
502
+ flash attention and deal with padding tokens in case the input contains any of them.
503
+ """
504
+
505
+ def __init__(self, *args, **kwargs):
506
+ super().__init__(*args, **kwargs)
507
+
508
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
509
+ # 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.
510
+ # 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).
511
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
512
+
513
+ def forward(
514
+ self,
515
+ hidden_states: torch.Tensor,
516
+ attention_mask: Optional[torch.LongTensor] = None,
517
+ position_ids: Optional[torch.LongTensor] = None,
518
+ past_key_value: Optional[Cache] = None,
519
+ output_attentions: bool = False,
520
+ use_cache: bool = False,
521
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
522
+ output_attentions = False
523
+
524
+ bsz, q_len, _ = hidden_states.size()
525
+ kv_seq_len = hidden_states.shape[-2]
526
+
527
+ past_key, past_value, beacon_size, beacon_indices = past_key_value
528
+ if past_key is not None:
529
+ past_seq_len = past_key.shape[2]
530
+ kv_seq_len += past_seq_len
531
+ else:
532
+ past_seq_len = 0
533
+
534
+ query_states, key_states, value_states = self.qkv_proj_with_beacon(hidden_states, beacon_size, beacon_indices)
535
+
536
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
537
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
538
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
539
+
540
+ # return keys and values before rope
541
+ # NOTE: incrementally return keys and values for efficiency
542
+ past_key_value = (key_states, value_states, beacon_size, beacon_indices)
543
+
544
+ if past_key is not None:
545
+ # reuse k, v, self_attention
546
+ key_states = torch.cat([past_key, key_states], dim=2)
547
+ value_states = torch.cat([past_value, value_states], dim=2)
548
+
549
+ query_states, key_states = self.rotary_emb(query_states, key_states, position_ids)
550
+
551
+ # FlashAttention will automatically handle grouped query attention
552
+ # key_states = repeat_kv(key_states, self.num_key_value_groups)
553
+ # value_states = repeat_kv(value_states, self.num_key_value_groups)
554
+
555
+ # 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
556
+ # to be able to avoid many of these transpose/reshape/view.
557
+ query_states = query_states.transpose(1, 2)
558
+ key_states = key_states.transpose(1, 2)
559
+ value_states = value_states.transpose(1, 2)
560
+
561
+ dropout_rate = self.attention_dropout if self.training else 0.0
562
+
563
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
564
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
565
+ # cast them back in the correct dtype just to be sure everything works as expected.
566
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
567
+ # in fp32. (Qwen2RMSNorm handles it correctly)
568
+
569
+ input_dtype = query_states.dtype
570
+ if input_dtype == torch.float32:
571
+ if torch.is_autocast_enabled():
572
+ target_dtype = torch.get_autocast_gpu_dtype()
573
+ # Handle the case where the model is quantized
574
+ elif hasattr(self.config, "_pre_quantization_dtype"):
575
+ target_dtype = self.config._pre_quantization_dtype
576
+ else:
577
+ target_dtype = self.q_proj.weight.dtype
578
+
579
+ logger.warning_once(
580
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
581
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
582
+ f" {target_dtype}."
583
+ )
584
+
585
+ query_states = query_states.to(target_dtype)
586
+ key_states = key_states.to(target_dtype)
587
+ value_states = value_states.to(target_dtype)
588
+
589
+ attn_output = self._flash_attention_forward(
590
+ query_states,
591
+ key_states,
592
+ value_states,
593
+ attention_mask,
594
+ q_len,
595
+ dropout=dropout_rate
596
+ )
597
+
598
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
599
+ attn_output = self.o_proj_with_beacon(attn_output, beacon_size, beacon_indices)
600
+
601
+ if not output_attentions:
602
+ attn_weights = None
603
+
604
+ return attn_output, attn_weights, past_key_value
605
+
606
+ def _flash_attention_forward(
607
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
608
+ ):
609
+ """
610
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
611
+ first unpad the input, then computes the attention scores and pad the final attention scores.
612
+
613
+ Args:
614
+ query_states (`torch.Tensor`):
615
+ Input query states to be passed to Flash Attention API
616
+ key_states (`torch.Tensor`):
617
+ Input key states to be passed to Flash Attention API
618
+ value_states (`torch.Tensor`):
619
+ Input value states to be passed to Flash Attention API
620
+ attention_mask (`torch.Tensor`):
621
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
622
+ position of padding tokens and 1 for the position of non-padding tokens.
623
+ dropout (`float`):
624
+ Attention dropout
625
+ softmax_scale (`float`, *optional*):
626
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
627
+ """
628
+ if not self._flash_attn_uses_top_left_mask:
629
+ causal = self.is_causal
630
+ else:
631
+ # 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__.
632
+ causal = self.is_causal and query_length != 1
633
+
634
+ # Contains at least one padding token in the sequence
635
+ if attention_mask is not None:
636
+ batch_size = query_states.shape[0]
637
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
638
+ query_states, key_states, value_states, attention_mask, query_length
639
+ )
640
+
641
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
642
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
643
+
644
+ attn_output_unpad = flash_attn_varlen_func(
645
+ query_states,
646
+ key_states,
647
+ value_states,
648
+ cu_seqlens_q=cu_seqlens_q,
649
+ cu_seqlens_k=cu_seqlens_k,
650
+ max_seqlen_q=max_seqlen_in_batch_q,
651
+ max_seqlen_k=max_seqlen_in_batch_k,
652
+ dropout_p=dropout,
653
+ softmax_scale=softmax_scale,
654
+ causal=causal,
655
+ )
656
+
657
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
658
+ else:
659
+ attn_output = flash_attn_func(
660
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
661
+ )
662
+
663
+ return attn_output
664
+
665
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
666
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
667
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
668
+
669
+ key_layer = index_first_axis(
670
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
671
+ )
672
+ value_layer = index_first_axis(
673
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
674
+ )
675
+ if query_length == kv_seq_len:
676
+ query_layer = index_first_axis(
677
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
678
+ )
679
+ cu_seqlens_q = cu_seqlens_k
680
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
681
+ indices_q = indices_k
682
+ elif query_length == 1:
683
+ max_seqlen_in_batch_q = 1
684
+ cu_seqlens_q = torch.arange(
685
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
686
+ ) # There is a memcpy here, that is very bad.
687
+ indices_q = cu_seqlens_q[:-1]
688
+ query_layer = query_layer.squeeze(1)
689
+ else:
690
+ # The -q_len: slice assumes left padding.
691
+ attention_mask = attention_mask[:, -query_length:]
692
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
693
+
694
+ return (
695
+ query_layer,
696
+ key_layer,
697
+ value_layer,
698
+ indices_q,
699
+ (cu_seqlens_q, cu_seqlens_k),
700
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
701
+ )
702
+
703
+
704
+ QWEN2_ATTENTION_CLASSES = {
705
+ "eager": Qwen2Attention,
706
+ "sdpa": Qwen2SdpaAttention,
707
+ "flash_attention_2": Qwen2FlashAttention2,
708
+ }
709
+
710
+
711
+ class Qwen2DecoderLayer(nn.Module):
712
+ def __init__(self, config: Qwen2Config, layer_idx: int):
713
+ super().__init__()
714
+ self.hidden_size = config.hidden_size
715
+
716
+ if config.use_sliding_window and config._attn_implementation != "flash_attention_2":
717
+ logger.warning_once(
718
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
719
+ "unexpected results may be encountered."
720
+ )
721
+ self.self_attn = QWEN2_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
722
+
723
+ self.mlp = Qwen2MLP(config)
724
+ self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
725
+ self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
726
+
727
+ def forward(
728
+ self,
729
+ hidden_states: torch.Tensor,
730
+ attention_mask: Optional[torch.Tensor] = None,
731
+ position_ids: Optional[torch.LongTensor] = None,
732
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
733
+ output_attentions: Optional[bool] = False,
734
+ use_cache: Optional[bool] = False,
735
+ **kwargs,
736
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
737
+ if "padding_mask" in kwargs:
738
+ warnings.warn(
739
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
740
+ "Please make sure use `attention_mask` instead.`"
741
+ )
742
+ """
743
+ Args:
744
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
745
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
746
+ `(batch, sequence_length)` where padding elements are indicated by 0.
747
+ output_attentions (`bool`, *optional*):
748
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
749
+ returned tensors for more detail.
750
+ use_cache (`bool`, *optional*):
751
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
752
+ (see `past_key_values`).
753
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
754
+ """
755
+ residual = hidden_states
756
+
757
+ hidden_states = self.input_layernorm(hidden_states)
758
+
759
+ # Self Attention
760
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
761
+ hidden_states=hidden_states,
762
+ attention_mask=attention_mask,
763
+ position_ids=position_ids,
764
+ past_key_value=past_key_value,
765
+ output_attentions=output_attentions,
766
+ use_cache=use_cache,
767
+ )
768
+ hidden_states = residual + hidden_states
769
+
770
+ # Fully Connected
771
+ residual = hidden_states
772
+ hidden_states = self.post_attention_layernorm(hidden_states)
773
+ hidden_states = self.mlp(hidden_states)
774
+ hidden_states = residual + hidden_states
775
+
776
+ outputs = (hidden_states,)
777
+
778
+ if output_attentions:
779
+ outputs += (self_attn_weights,)
780
+
781
+ if use_cache:
782
+ outputs += (present_key_value,)
783
+
784
+ return outputs
785
+
786
+
787
+ QWEN2_START_DOCSTRING = r"""
788
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
789
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
790
+ etc.)
791
+
792
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
793
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
794
+ and behavior.
795
+
796
+ Parameters:
797
+ config ([`Qwen2Config`]):
798
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
799
+ load the weights associated with the model, only the configuration. Check out the
800
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
801
+ """
802
+
803
+
804
+ @add_start_docstrings(
805
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
806
+ QWEN2_START_DOCSTRING,
807
+ )
808
+ class Qwen2PreTrainedModel(PreTrainedModel):
809
+ config_class = Qwen2Config
810
+ base_model_prefix = "model"
811
+ supports_gradient_checkpointing = True
812
+ _no_split_modules = ["Qwen2DecoderLayer"]
813
+ _skip_keys_device_placement = "past_key_values"
814
+ _supports_flash_attn_2 = True
815
+ _supports_sdpa = True
816
+ _supports_cache_class = True
817
+
818
+ def _init_weights(self, module):
819
+ std = self.config.initializer_range
820
+ if isinstance(module, nn.Linear):
821
+ module.weight.data.normal_(mean=0.0, std=std)
822
+ if module.bias is not None:
823
+ module.bias.data.zero_()
824
+ elif isinstance(module, nn.Embedding):
825
+ module.weight.data.normal_(mean=0.0, std=std)
826
+ if module.padding_idx is not None:
827
+ module.weight.data[module.padding_idx].zero_()
828
+
829
+
830
+ QWEN2_INPUTS_DOCSTRING = r"""
831
+ Args:
832
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
833
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
834
+ it.
835
+
836
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
837
+ [`PreTrainedTokenizer.__call__`] for details.
838
+
839
+ [What are input IDs?](../glossary#input-ids)
840
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
841
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
842
+
843
+ - 1 for tokens that are **not masked**,
844
+ - 0 for tokens that are **masked**.
845
+
846
+ [What are attention masks?](../glossary#attention-mask)
847
+
848
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
849
+ [`PreTrainedTokenizer.__call__`] for details.
850
+
851
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
852
+ `past_key_values`).
853
+
854
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
855
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
856
+ information on the default strategy.
857
+
858
+ - 1 indicates the head is **not masked**,
859
+ - 0 indicates the head is **masked**.
860
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
861
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
862
+ config.n_positions - 1]`.
863
+
864
+ [What are position IDs?](../glossary#position-ids)
865
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
866
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
867
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
868
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
869
+
870
+ Two formats are allowed:
871
+ - a [`~cache_utils.Cache`] instance;
872
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
873
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
874
+ cache format.
875
+
876
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
877
+ legacy cache format will be returned.
878
+
879
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
880
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
881
+ of shape `(batch_size, sequence_length)`.
882
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
883
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
884
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
885
+ model's internal embedding lookup matrix.
886
+ use_cache (`bool`, *optional*):
887
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
888
+ `past_key_values`).
889
+ output_attentions (`bool`, *optional*):
890
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
891
+ tensors for more detail.
892
+ output_hidden_states (`bool`, *optional*):
893
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
894
+ more detail.
895
+ return_dict (`bool`, *optional*):
896
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
897
+ """
898
+
899
+
900
+ @add_start_docstrings(
901
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
902
+ QWEN2_START_DOCSTRING,
903
+ )
904
+ class Qwen2Model(Qwen2PreTrainedModel):
905
+ """
906
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
907
+
908
+ Args:
909
+ config: Qwen2Config
910
+ """
911
+
912
+ def __init__(self, config: Qwen2Config):
913
+ super().__init__(config)
914
+ self.padding_idx = config.pad_token_id
915
+ self.vocab_size = config.vocab_size
916
+
917
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
918
+
919
+ # BEACON: add beacon embedding
920
+ self.beacon_embed_tokens = nn.Embedding(1, config.hidden_size, self.padding_idx)
921
+ self.beacon_embed_tokens._is_hf_initialized = True
922
+
923
+ self.layers = nn.ModuleList(
924
+ [Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
925
+ )
926
+ self._attn_implementation = config._attn_implementation
927
+ self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
928
+
929
+ self.gradient_checkpointing = False
930
+ # Initialize weights and apply final processing
931
+ self.post_init()
932
+
933
+ def _init_beacon_embed(self, missing_keys):
934
+ """Initialize the beacon token embedding with that of the eos token."""
935
+ if is_deepspeed_zero3_enabled():
936
+ import deepspeed
937
+ params = [self.beacon_embed_tokens.weight, self.embed_tokens.weight]
938
+ with deepspeed.zero.GatheredParameters(params, modifier_rank=0):
939
+ # deepspeed will initialize the parameters to zero
940
+ if (self.beacon_embed_tokens.weight == 0).all():
941
+ if self.config.beacon_embed_init == "bos":
942
+ self.beacon_embed_tokens.weight.data[:] = self.embed_tokens.weight.data[self.config.bos_token_id]
943
+ elif self.config.beacon_embed_init == "eos":
944
+ if isinstance(self.config.eos_token_id, list):
945
+ eos_token_id = self.config.eos_token_id[0]
946
+ else:
947
+ eos_token_id = self.config.eos_token_id
948
+ self.beacon_embed_tokens.weight.data[:] = self.embed_tokens.weight.data[eos_token_id]
949
+ else:
950
+ raise NotImplementedError(f"Make sure beacon_embed_init is either eos or bos, found {self.config.beacon_embed_init}")
951
+ else:
952
+ if any("beacon_embed_tokens" in missing_key for missing_key in missing_keys):
953
+ if self.config.beacon_embed_init == "bos":
954
+ self.beacon_embed_tokens.weight.data[:] = self.embed_tokens.weight.data[self.config.bos_token_id]
955
+ elif self.config.beacon_embed_init == "eos":
956
+ if isinstance(self.config.eos_token_id, list):
957
+ eos_token_id = self.config.eos_token_id[0]
958
+ else:
959
+ eos_token_id = self.config.eos_token_id
960
+ self.beacon_embed_tokens.weight.data[:] = self.embed_tokens.weight.data[eos_token_id]
961
+ else:
962
+ raise NotImplementedError(f"Make sure beacon_embed_init is either eos or bos, found {self.config.beacon_embed_init}")
963
+
964
+ def get_input_embeddings(self):
965
+ return self.embed_tokens
966
+
967
+ def set_input_embeddings(self, value):
968
+ self.embed_tokens = value
969
+
970
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
971
+ def forward(
972
+ self,
973
+ input_ids: torch.LongTensor = None,
974
+ attention_mask: Optional[torch.Tensor] = None,
975
+ position_ids: Optional[torch.LongTensor] = None,
976
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
977
+ inputs_embeds: Optional[torch.FloatTensor] = None,
978
+ use_cache: Optional[bool] = None,
979
+ output_attentions: Optional[bool] = None,
980
+ output_hidden_states: Optional[bool] = None,
981
+ return_dict: Optional[bool] = None,
982
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
983
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
984
+ output_hidden_states = (
985
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
986
+ )
987
+ # BEACON: always use cache
988
+ use_cache = True
989
+
990
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
991
+
992
+ # retrieve input_ids and inputs_embeds
993
+ if input_ids is not None and inputs_embeds is not None:
994
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
995
+ elif input_ids is not None:
996
+ batch_size, seq_length = input_ids.shape[:2]
997
+ elif inputs_embeds is not None:
998
+ batch_size, seq_length = inputs_embeds.shape[:2]
999
+ else:
1000
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1001
+
1002
+ past_key, past_value, beacon_size, beacon_indices = past_key_values[0]
1003
+
1004
+ # BEACON: separately embed ordinal tokens and beacon tokens because ordinal tokens do not receive gradients
1005
+ if beacon_size > 0:
1006
+ # 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
1007
+ cur_beacon_indices = beacon_indices[-input_ids.shape[1]:]
1008
+
1009
+ ordinal_input_ids = input_ids[:, cur_beacon_indices == 0]
1010
+ beacon_input_ids = input_ids[:, cur_beacon_indices > 0]
1011
+ ordinal_inputs_embeds = self.embed_tokens(ordinal_input_ids)
1012
+ beacon_input_embeds = self.beacon_embed_tokens(beacon_input_ids - self.config.vocab_size)
1013
+ # create a new embedding tensor
1014
+ inputs_embeds = beacon_input_embeds.new_zeros(*input_ids.shape, beacon_input_embeds.shape[-1])
1015
+ inputs_embeds[:, cur_beacon_indices == 0] = ordinal_inputs_embeds
1016
+ inputs_embeds[:, cur_beacon_indices > 0] = beacon_input_embeds
1017
+
1018
+ else:
1019
+ inputs_embeds = self.embed_tokens(input_ids)
1020
+
1021
+ # embed positions
1022
+ hidden_states = inputs_embeds
1023
+
1024
+ # print(f"input_ids: {input_ids}")
1025
+ # print(f"beacon_indices: {beacon_indices}")
1026
+ # print(f"position_ids: {position_ids}")
1027
+ # print(f"attention_mask:\n{attention_mask == 0}")
1028
+ # x = input()
1029
+ # if x == "s":
1030
+ # return
1031
+
1032
+ # decoder layers
1033
+ all_hidden_states = () if output_hidden_states else None
1034
+ all_self_attns = () if output_attentions else None
1035
+ # BEACON: still use tuple to organize cache
1036
+ next_decoder_cache = () if use_cache else None
1037
+
1038
+ for idx, decoder_layer in enumerate(self.layers):
1039
+ if output_hidden_states:
1040
+ all_hidden_states += (hidden_states,)
1041
+
1042
+ # BEACON: slice out the past_key_value of the corresponding layer
1043
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
1044
+
1045
+ if self.gradient_checkpointing and self.training:
1046
+ layer_outputs = self._gradient_checkpointing_func(
1047
+ decoder_layer.__call__,
1048
+ hidden_states,
1049
+ attention_mask,
1050
+ position_ids,
1051
+ past_key_value,
1052
+ output_attentions,
1053
+ use_cache,
1054
+ )
1055
+ else:
1056
+ layer_outputs = decoder_layer(
1057
+ hidden_states,
1058
+ attention_mask=attention_mask,
1059
+ position_ids=position_ids,
1060
+ past_key_value=past_key_value,
1061
+ output_attentions=output_attentions,
1062
+ use_cache=use_cache,
1063
+ )
1064
+
1065
+ hidden_states = layer_outputs[0]
1066
+
1067
+ if use_cache:
1068
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
1069
+
1070
+ if output_attentions:
1071
+ all_self_attns += (layer_outputs[1],)
1072
+
1073
+ hidden_states = self.norm(hidden_states)
1074
+
1075
+ # add hidden states from the last decoder layer
1076
+ if output_hidden_states:
1077
+ all_hidden_states += (hidden_states,)
1078
+
1079
+ next_cache = next_decoder_cache if use_cache else None
1080
+
1081
+ if not return_dict:
1082
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1083
+ return BaseModelOutputWithPast(
1084
+ last_hidden_state=hidden_states,
1085
+ past_key_values=next_cache,
1086
+ hidden_states=all_hidden_states,
1087
+ attentions=all_self_attns,
1088
+ )
1089
+
1090
+
1091
+ class Qwen2ForCausalLM(Qwen2PreTrainedModel):
1092
+ _tied_weights_keys = ["lm_head.weight"]
1093
+
1094
+ def __init__(self, config):
1095
+ super().__init__(config)
1096
+ self.model = Qwen2Model(config)
1097
+ self.vocab_size = config.vocab_size
1098
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1099
+ # Initialize weights and apply final processing
1100
+ self.post_init()
1101
+
1102
+ def get_input_embeddings(self):
1103
+ return self.model.embed_tokens
1104
+
1105
+ def set_input_embeddings(self, value):
1106
+ self.model.embed_tokens = value
1107
+
1108
+ def get_output_embeddings(self):
1109
+ return self.lm_head
1110
+
1111
+ def set_output_embeddings(self, new_embeddings):
1112
+ self.lm_head = new_embeddings
1113
+
1114
+ def set_decoder(self, decoder):
1115
+ self.model = decoder
1116
+
1117
+ def get_decoder(self):
1118
+ return self.model
1119
+
1120
+ @classmethod
1121
+ def from_pretrained(cls, *args, **kwargs):
1122
+ """Override the default from_pretrained to extend vocab size according to beacon_size."""
1123
+ kwargs.update(output_loading_info=True)
1124
+ model, loading_info = super().from_pretrained(*args, **kwargs)
1125
+
1126
+ # NOTE: set memory after from_pretrained because there may be another transformer model inside the Memory object, which may cause weird erros during loading
1127
+ config = model.config
1128
+ model.memory = Memory(
1129
+ model_config=config,
1130
+ k_seq_dim=2,
1131
+ v_seq_dim=2,
1132
+ )
1133
+
1134
+ missing_keys = loading_info["missing_keys"]
1135
+ # NOTE: the beacon parameters may or may not be loaded from the checkpoint
1136
+ # if it is loaded from the checkpoint, we should not re-initilize it
1137
+ model.model._init_beacon_embed(missing_keys)
1138
+ # initialize weights of possible q,k,v,o,mlp
1139
+ for layer in model.model.layers:
1140
+ layer.self_attn._init_beacon_proj(missing_keys)
1141
+
1142
+ return model
1143
+
1144
+ def _native_forward(
1145
+ self,
1146
+ input_ids: torch.LongTensor = None,
1147
+ attention_mask: Optional[torch.Tensor] = None,
1148
+ position_ids: Optional[torch.LongTensor] = None,
1149
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1150
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1151
+ labels: Optional[torch.LongTensor] = None,
1152
+ use_cache: Optional[bool] = None,
1153
+ output_attentions: Optional[bool] = None,
1154
+ output_hidden_states: Optional[bool] = None,
1155
+ return_dict: Optional[bool] = None,
1156
+ ) -> Union[Tuple, ModelOutput]:
1157
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1158
+ output_hidden_states = (
1159
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1160
+ )
1161
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1162
+
1163
+ # when we directly call _native_forward, the past_key_values would be None
1164
+ if past_key_values is None:
1165
+ # NOTE: set beacon size to 0 to avoid using any beacon parameters, see Qwen2Attention.forward
1166
+ past_key_values = [(None, None, 0, None) for _ in range(self.config.num_hidden_layers)]
1167
+
1168
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1169
+ outputs = self.model(
1170
+ input_ids=input_ids,
1171
+ attention_mask=attention_mask,
1172
+ position_ids=position_ids,
1173
+ past_key_values=past_key_values,
1174
+ inputs_embeds=inputs_embeds,
1175
+ use_cache=use_cache,
1176
+ output_attentions=output_attentions,
1177
+ output_hidden_states=output_hidden_states,
1178
+ return_dict=return_dict,
1179
+ )
1180
+
1181
+ hidden_states = outputs[0]
1182
+ logits = self.lm_head(hidden_states)
1183
+ logits = logits.float()
1184
+
1185
+ loss = None
1186
+ batch_loss = None
1187
+ token_loss = None
1188
+
1189
+ if labels is not None:
1190
+ loss, batch_loss, token_loss = compute_loss(logits, labels, shift=False)
1191
+
1192
+ if not return_dict:
1193
+ output = (logits,) + outputs[1:]
1194
+ return (loss,) + output if loss is not None else output
1195
+
1196
+ return ModelOutput(
1197
+ loss=loss,
1198
+ batch_loss=batch_loss,
1199
+ token_loss=token_loss,
1200
+ logits=logits,
1201
+ past_key_values=outputs.past_key_values,
1202
+ hidden_states=outputs.hidden_states,
1203
+ attentions=outputs.attentions,
1204
+ )
1205
+
1206
+ def _beacon_forward(self,
1207
+ input_ids: torch.LongTensor = None,
1208
+ attention_mask: Optional[torch.Tensor] = None,
1209
+ position_ids: Optional[torch.LongTensor] = None,
1210
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1211
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1212
+ labels: Optional[torch.LongTensor] = None,
1213
+ use_cache: Optional[bool] = None,
1214
+ output_attentions: Optional[bool] = None,
1215
+ output_hidden_states: Optional[bool] = None,
1216
+ return_dict: Optional[bool] = None,
1217
+ beacon_skip_first: Optional[int] = None,
1218
+ beacon_skip_last: Optional[int] = None,
1219
+ ):
1220
+ # t1 = time.time()
1221
+
1222
+ # initialize cache
1223
+ self.memory.prepare(
1224
+ input_ids=input_ids,
1225
+ attention_mask=attention_mask,
1226
+ labels=labels,
1227
+ skip_first=beacon_skip_first,
1228
+ skip_last=beacon_skip_last,
1229
+ )
1230
+
1231
+ # t2 = time.time()
1232
+
1233
+ while not self.memory.finish:
1234
+
1235
+ # t3 = time.time()
1236
+
1237
+ input_ids, attention_mask, position_ids, past_key_values, labels = self.memory.step()
1238
+
1239
+ # t4 = time.time()
1240
+
1241
+ outputs = self._native_forward(
1242
+ input_ids=input_ids,
1243
+ attention_mask=attention_mask,
1244
+ position_ids=position_ids,
1245
+ past_key_values=past_key_values,
1246
+ inputs_embeds=inputs_embeds,
1247
+ use_cache=use_cache,
1248
+ output_attentions=output_attentions,
1249
+ output_hidden_states=output_hidden_states,
1250
+ return_dict=return_dict,
1251
+ labels=labels,
1252
+ )
1253
+
1254
+ # t5 = time.time()
1255
+
1256
+ # update past_key_values
1257
+ self.memory.update_memory(outputs.past_key_values)
1258
+
1259
+ # t6 = time.time()
1260
+
1261
+ if labels is not None:
1262
+ # update loss
1263
+ self.memory.update_loss(outputs.batch_loss, (labels != -100).sum(-1))
1264
+
1265
+ # t7 = time.time()
1266
+
1267
+ # print(f"step time: {t4-t3}, forward time: {t5-t4}, update time: {t6-t5}, loss time: {t7-t6}")
1268
+ # input()
1269
+
1270
+ # t8 = time.time()
1271
+
1272
+ # output loss, past_key_values, and perplexity
1273
+ outputs = self.memory.output(outputs)
1274
+
1275
+ # t9 = time.time()
1276
+
1277
+ # print(f"output time: {t9-t8}")
1278
+ # input()
1279
+
1280
+ return outputs
1281
+
1282
+ def forward(self, **kwargs):
1283
+ """Forward computation over a batch of sequences.
1284
+ """
1285
+ # only allow gradient when training
1286
+ with optional_grad_ctx(with_grad=self.training):
1287
+ # we can disable beacon to use the original mistral
1288
+ if hasattr(self, "_enable_beacon") and self._enable_beacon == False:
1289
+ return self._native_forward(**kwargs)
1290
+ else:
1291
+ return self._beacon_forward(**kwargs)
1292
+
1293
+ def prepare_inputs_for_generation(
1294
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, beacon_skip_first=None, beacon_skip_last=None, **kwargs
1295
+ ):
1296
+ if past_key_values:
1297
+ input_ids = input_ids[:, -1:]
1298
+
1299
+ model_inputs = {"input_ids": input_ids, "beacon_skip_first": beacon_skip_first, "beacon_skip_last": beacon_skip_last}
1300
+ return model_inputs
1301
+
1302
+ @staticmethod
1303
+ def _reorder_cache(past_key_values, beam_idx):
1304
+ reordered_past = ()
1305
+ for layer_past in past_key_values:
1306
+ reordered_past += (
1307
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1308
+ )
1309
+ return reordered_past
modeling_utils.py ADDED
@@ -0,0 +1,711 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 get_shifted_labels(input_ids):
33
+ if isinstance(input_ids, torch.Tensor):
34
+ labels = input_ids.clone()
35
+ labels = torch.cat([labels[:, 1:], labels.new_zeros((input_ids.shape[0], 1)) - 100], dim=-1)
36
+ elif isinstance(input_ids, list) and isinstance(input_ids[0], int):
37
+ labels = input_ids.copy()
38
+ labels = labels[1:] + [-100]
39
+ elif isinstance(input_ids, list) and isinstance(input_ids[0], list):
40
+ labels = input_ids.copy()
41
+ for i, label in enumerate(labels):
42
+ labels[i] = labels[i][1:] + [-100]
43
+ else:
44
+ raise NotImplementedError
45
+ return labels
46
+
47
+ def compute_loss(logits, labels, shift=False):
48
+ """
49
+ Returns:
50
+ token_loss: batch_size, seq_length
51
+ """
52
+ if shift:
53
+ labels = get_shifted_labels(labels)
54
+
55
+ labels = labels.to(logits.device)
56
+ batch_size = logits.shape[0]
57
+
58
+ # NOTE: the loss on -100 labels is 0 by default
59
+ token_loss = torch.nn.functional.cross_entropy(
60
+ logits.flatten(0, 1),
61
+ labels.reshape(-1),
62
+ reduction="none"
63
+ ).reshape(batch_size, -1) # batch_size, seq_len
64
+
65
+ # print(token_loss)
66
+
67
+ valid_token_num = (labels != -100).sum(-1) # batch_size
68
+ all_valid_token_num = valid_token_num.sum()
69
+
70
+ if all_valid_token_num > 0:
71
+ loss = token_loss.sum() / valid_token_num.sum()
72
+ else:
73
+ loss = token_loss.sum()
74
+
75
+ batch_loss = token_loss.sum(-1) / valid_token_num
76
+ # prevent nan
77
+ if (valid_token_num == 0).any():
78
+ batch_loss = batch_loss.masked_fill(valid_token_num == 0, 0.)
79
+
80
+ return loss, batch_loss, token_loss
81
+
82
+
83
+ @torch.no_grad()
84
+ def evaluate_perplexity(model, dataloader, accelerator:Optional[Accelerator]=None):
85
+ if accelerator is not None and type(dataloader) == torch.utils.data.DataLoader:
86
+ # if the dataloader has been prepared, we shall not prepare it twice, especially in case of deepspeed
87
+ dataloader = accelerator.prepare(dataloader)
88
+
89
+ # if accelerator.process_index == 0:
90
+ # for name, x in model.named_parameters():
91
+ # print(f"{name: ^80} {x.dtype}")
92
+
93
+ all_loss = defaultdict(list)
94
+ for i, x in enumerate(tqdm(dataloader, desc="Computing Perplexity")):
95
+ # NOTE: important to reset memory for every batch
96
+ if hasattr(model, "memory"):
97
+ model.memory.reset()
98
+
99
+ # the seq id
100
+ index = x.pop("index")
101
+ # length is used to group training data, no use here
102
+ length = x.pop("length", None)
103
+
104
+ output = model(**x)
105
+
106
+ valid_token_num = (x["labels"] != -100).sum(-1)
107
+
108
+ # NOTE: we need the loss for each element in the batch for accurate computation, because the number of valid tokens may differ among elements
109
+ if hasattr(output, "batch_loss"):
110
+ # output from our model has batch_loss by default
111
+ batch_loss = output.batch_loss
112
+ else:
113
+ # output from other models does not
114
+ loss, batch_loss, token_loss = compute_loss(output.logits, x["labels"], shift=True)
115
+
116
+ index = index.tolist()
117
+ batch_loss = batch_loss.tolist()
118
+ valid_token_num = valid_token_num.tolist()
119
+
120
+ if accelerator is not None and accelerator.num_processes > 1:
121
+ # num_device * batch_size
122
+ index = accelerator.gather_for_metrics(index)
123
+ batch_loss = accelerator.gather_for_metrics(batch_loss)
124
+ valid_token_num = accelerator.gather_for_metrics(valid_token_num)
125
+
126
+ for _id, _loss, _num in zip(index, batch_loss, valid_token_num):
127
+ # loss times num is the total loss of all valid tokens
128
+ all_loss[_id].append((_loss * _num, _num))
129
+
130
+ all_loss = dict(all_loss)
131
+ for _id, loss_and_num in all_loss.items():
132
+ # sum up the loss for all valid tokens in the entire sequence, and divide the number of valid tokens
133
+ all_loss[_id] = sum([x[0] for x in loss_and_num]) / sum(x[1] for x in loss_and_num)
134
+
135
+ # average across then take exp
136
+ perplexity = math.exp(sum(all_loss.values()) / len(all_loss))
137
+ return perplexity
138
+
139
+
140
+ @torch.no_grad()
141
+ def evaluate_generation(model, dataloader, accelerator:Optional[Accelerator]=None, tokenizer=None, return_new_tokens_only=True, **generation_config):
142
+ if accelerator is not None and type(dataloader) == torch.utils.data.DataLoader:
143
+ # if the dataloader has been prepared, we shall not prepare it twice, especially in case of deepspeed
144
+ dataloader = accelerator.prepare(dataloader)
145
+
146
+ all_indices = []
147
+ all_outputs = []
148
+
149
+ index = 0
150
+
151
+ for i, x in enumerate(tqdm(dataloader, desc="Computing Generation")):
152
+ # if i > 3:
153
+ # break
154
+
155
+ # NOTE: important to reset memory for every batch
156
+ if hasattr(model, "memory"):
157
+ model.memory.reset()
158
+
159
+ # length is used to group training data, no use here
160
+ length = x.pop("length", None)
161
+
162
+ # if indices are None, we use batch size
163
+ indices = x.pop("index", None)
164
+ if indices is None:
165
+ indices = list(range(index, index + x['input_ids'].shape[0]))
166
+ index += x['input_ids'].shape[0]
167
+ else:
168
+ indices = indices.tolist()
169
+
170
+ outputs = model.generate(**x, **generation_config)
171
+ if return_new_tokens_only:
172
+ start_idx = x["input_ids"].shape[1]
173
+ outputs = outputs[:, start_idx:]
174
+
175
+ outputs = tokenizer.batch_decode(outputs, skip_special_tokens=True)
176
+
177
+ if accelerator is not None and accelerator.num_processes > 1:
178
+ outputs = accelerator.gather_for_metrics(outputs)
179
+ indices = accelerator.gather_for_metrics(indices)
180
+
181
+ outputs = outputs
182
+ indices = indices
183
+ all_indices.extend(indices)
184
+ all_outputs.extend(outputs)
185
+
186
+ return all_indices, all_outputs
187
+
188
+
189
+ @torch.no_grad()
190
+ def evaluate_nll(model, dataloader, accelerator:Optional[Accelerator]=None):
191
+ if accelerator is not None and type(dataloader) == torch.utils.data.DataLoader:
192
+ # if the dataloader has been prepared, we shall not prepare it twice, especially in case of deepspeed
193
+ dataloader = accelerator.prepare(dataloader)
194
+
195
+ # if accelerator.process_index == 0:
196
+ # for name, x in model.named_parameters():
197
+ # print(f"{name: ^80} {x.dtype}")
198
+
199
+ all_loss = defaultdict(list)
200
+ for i, x in enumerate(tqdm(dataloader, desc="Computing Perplexity")):
201
+ # NOTE: important to reset memory for every batch
202
+ if hasattr(model, "memory"):
203
+ model.memory.reset()
204
+
205
+ # the seq id
206
+ index = x.pop("index")
207
+ # length is used to group training data, no use here
208
+ length = x.pop("length", None)
209
+
210
+ output = model(**x)
211
+
212
+ valid_token_num = (x["labels"] != -100).sum()
213
+
214
+ # NOTE: we need the loss for each element in the batch for accurate computation, because the number of valid tokens may differ among elements
215
+ if hasattr(output, "batch_loss"):
216
+ # output from our model has batch_loss by default
217
+ batch_loss = output.batch_loss
218
+ else:
219
+ # output from other models does not
220
+ loss, batch_loss, token_loss = compute_loss(output.logits, x["labels"], shift=True)
221
+
222
+ if accelerator is not None and accelerator.num_processes > 1:
223
+ # num_device * batch_size
224
+ index = accelerator.gather_for_metrics(index)
225
+ batch_loss = accelerator.gather_for_metrics(batch_loss)
226
+ valid_token_num = accelerator.gather_for_metrics(valid_token_num)
227
+
228
+ for _id, _loss in zip(index.tolist(), batch_loss.tolist()):
229
+ # loss times num is the total loss of all valid tokens
230
+ all_loss[_id].append(_loss)
231
+
232
+ return all_loss
233
+
234
+
235
+ @dataclass
236
+ class ModelOutput(BaseModelOutputWithPast):
237
+ loss: Optional[torch.FloatTensor] = None
238
+ batch_loss: Optional[torch.FloatTensor] = None
239
+ token_loss: Optional[torch.FloatTensor] = None
240
+ logits: torch.FloatTensor = None
241
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
242
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
243
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
244
+
245
+
246
+
247
+ ########## Various RoPE Scaling Methods Below (wrap the encoding process within the module for convenience) ##########
248
+
249
+ def get_rope(head_dim, base, max_position_embeddings, rope_scaling=None):
250
+ """
251
+ Get rope module. {native, linear scaling, dynamic ntk scaling, yarn scaling, llama3 scaling}
252
+ """
253
+ if rope_scaling is None:
254
+ rope = RotaryEmbedding(
255
+ dim=head_dim,
256
+ base=base,
257
+ max_position_embeddings=max_position_embeddings,
258
+ )
259
+ else:
260
+ scaling_type = rope_scaling["type"]
261
+ scaling_factor = rope_scaling["factor"]
262
+ if scaling_type == "linear":
263
+ rope = LinearScalingRotaryEmbedding(
264
+ dim=head_dim,
265
+ base=base,
266
+ max_position_embeddings=max_position_embeddings,
267
+ scaling_factor=scaling_factor,
268
+ )
269
+ elif scaling_type == "dynamic":
270
+ rope = DynamicNTKScalingRotaryEmbedding(
271
+ dim=head_dim,
272
+ base=base,
273
+ max_position_embeddings=max_position_embeddings,
274
+ scaling_factor=scaling_factor,
275
+ )
276
+ elif scaling_type == "yarn":
277
+ rope = YarnRotaryEmbedding(
278
+ dim=head_dim,
279
+ base=base,
280
+ max_position_embeddings=max_position_embeddings,
281
+ scaling_factor=scaling_factor,
282
+ )
283
+ elif scaling_type == "yarn-t":
284
+ rope = YarnDynamicTemperatureRotaryEmbedding(
285
+ dim=head_dim,
286
+ base=base,
287
+ max_position_embeddings=max_position_embeddings,
288
+ scaling_factor=scaling_factor,
289
+ )
290
+ elif scaling_type == "yarn-t-logn":
291
+ rope = YarnDynamicTemperatureLogNRotaryEmbedding(
292
+ dim=head_dim,
293
+ base=base,
294
+ max_position_embeddings=max_position_embeddings,
295
+ scaling_factor=scaling_factor,
296
+ )
297
+ elif scaling_type == "llama3":
298
+ rope = Llama3RotaryEmbedding(
299
+ dim=head_dim,
300
+ base=base,
301
+ max_position_embeddings=max_position_embeddings,
302
+ scaling_factor=scaling_factor,
303
+ original_max_position_embeddings=rope_scaling.get("original_max_position_embeddings", 8192),
304
+ low_freq_factor=rope_scaling.get("low_freq_factor", 1),
305
+ high_freq_factor=rope_scaling.get("high_freq_factor", 4),
306
+ )
307
+ else:
308
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
309
+
310
+ return rope
311
+
312
+
313
+ def rotate_half(x):
314
+ """Rotates half the hidden dims of the input."""
315
+ x1 = x[..., : x.shape[-1] // 2]
316
+ x2 = x[..., x.shape[-1] // 2 :]
317
+ return torch.cat((-x2, x1), dim=-1)
318
+
319
+
320
+ class RotaryEmbedding(torch.nn.Module):
321
+ def __init__(self, dim, max_position_embeddings=32768, base=10000, device=None):
322
+ super().__init__()
323
+
324
+ self.dim = dim
325
+ self.max_position_embeddings = max_position_embeddings
326
+ self.base = base
327
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.float32).to(device) / self.dim))
328
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
329
+
330
+ # Build here to make `torch.jit.trace` work.
331
+ self._set_cos_sin_cache(
332
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
333
+ )
334
+
335
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
336
+ self.max_seq_len_cached = seq_len
337
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.float32)
338
+ freqs = torch.outer(t, self.inv_freq)
339
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
340
+ emb = torch.cat((freqs, freqs), dim=-1)
341
+ self.register_buffer("cos_cached", emb.cos(), persistent=False)
342
+ self.register_buffer("sin_cached", emb.sin(), persistent=False)
343
+
344
+ def forward(self, q, k, position_ids):
345
+ seq_len = max(position_ids.max().item() + 1, k.shape[2])
346
+
347
+ # x: [bs, num_attention_heads, seq_len, head_size]
348
+ if seq_len > self.max_seq_len_cached:
349
+ self._set_cos_sin_cache(seq_len=seq_len, device=k.device, dtype=k.dtype)
350
+
351
+ # batch_size, 1, key_len, head_dim
352
+ k_cos = self.cos_cached[position_ids].to(dtype=k.dtype).unsqueeze(1)
353
+ k_sin = self.sin_cached[position_ids].to(dtype=k.dtype).unsqueeze(1)
354
+
355
+ q_cos = k_cos[..., -q.shape[2]:, :]
356
+ q_sin = k_sin[..., -q.shape[2]:, :]
357
+
358
+ q_embed = (q * q_cos) + (rotate_half(q) * q_sin)
359
+ k_embed = (k * k_cos) + (rotate_half(k) * k_sin)
360
+ return q_embed, k_embed
361
+
362
+
363
+ class LinearScalingRotaryEmbedding(RotaryEmbedding):
364
+ """RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
365
+
366
+ def __init__(self, dim, max_position_embeddings=32768, base=10000, device=None, scaling_factor=1.0):
367
+ self.scaling_factor = scaling_factor
368
+ super().__init__(dim, max_position_embeddings, base, device)
369
+
370
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
371
+ self.max_seq_len_cached = seq_len
372
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.float32)
373
+ t = t / self.scaling_factor
374
+
375
+ freqs = torch.outer(t, self.inv_freq)
376
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
377
+ emb = torch.cat((freqs, freqs), dim=-1)
378
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
379
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
380
+
381
+
382
+ class DynamicNTKScalingRotaryEmbedding(RotaryEmbedding):
383
+ """RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
384
+
385
+ def __init__(self, dim, max_position_embeddings=32768, base=10000, device=None, scaling_factor=1.0):
386
+ self.scaling_factor = scaling_factor
387
+ super().__init__(dim, max_position_embeddings, base, device)
388
+
389
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
390
+ self.max_seq_len_cached = seq_len
391
+
392
+ if seq_len > self.max_position_embeddings:
393
+ base = self.base * (
394
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
395
+ ) ** (self.dim / (self.dim - 2))
396
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2, dtype=torch.float32).to(device) / self.dim))
397
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
398
+
399
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
400
+
401
+ freqs = torch.outer(t, self.inv_freq)
402
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
403
+ emb = torch.cat((freqs, freqs), dim=-1)
404
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
405
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
406
+
407
+
408
+ class YarnRotaryEmbedding(torch.nn.Module):
409
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0, beta_slow=2, beta_fast=128):
410
+ super().__init__()
411
+
412
+ self.base = base
413
+ self.dim = dim
414
+ self.scaling_factor = scaling_factor
415
+ self.beta_slow = beta_slow
416
+ self.beta_fast = beta_fast
417
+ self.max_position_embeddings = max_position_embeddings
418
+
419
+ self._set_cos_sin_cache(
420
+ seq_len=math.ceil(max_position_embeddings * scaling_factor), device=device, dtype=torch.get_default_dtype()
421
+ )
422
+
423
+ def _get_factor(self):
424
+ # the dimension whose index is smaller than fast_dim rotates more than beta_fast
425
+ fast_dim = self.dim / 2 * (math.log(self.max_position_embeddings / (2 * math.pi * self.beta_fast)) / math.log(self.base))
426
+ fast_dim = max(math.floor(fast_dim), 0)
427
+ # the dimension whose index is bigger than slow_dim rotates less than beta_slow
428
+ slow_dim = self.dim / 2 * (math.log(self.max_position_embeddings / (2 * math.pi * self.beta_slow)) / math.log(self.base))
429
+ slow_dim = min(math.ceil(slow_dim), self.dim - 1)
430
+
431
+ if fast_dim == slow_dim:
432
+ slow_dim += 0.001
433
+
434
+ # NOTE: very important to use full precision here so that the factor is correct
435
+ dim_arange = torch.arange(0, self.dim // 2, dtype=torch.float32)
436
+ dim_factor = (dim_arange - fast_dim) / (slow_dim - fast_dim)
437
+ dim_factor = torch.clamp(dim_factor, 0, 1)
438
+
439
+ # align with the paper notation
440
+ return (1 - dim_factor)
441
+
442
+ def _get_temperature(self):
443
+ if self.scaling_factor <= 1:
444
+ return 1.0
445
+ return 0.07 * math.log(self.scaling_factor) + 1.0
446
+
447
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
448
+ dim_arange = torch.arange(0, self.dim, 2, device=device, dtype=torch.float32) / self.dim
449
+ # dim / 2
450
+ freq = self.base ** dim_arange
451
+ theta = 1 / freq
452
+ interleave_theta = theta / self.scaling_factor
453
+
454
+ factor = self._get_factor().to(device)
455
+ yarn_theta = factor * theta + (1 - factor) * interleave_theta
456
+ self.register_buffer("inv_freq", yarn_theta, persistent=False)
457
+
458
+ t = torch.arange(seq_len, device=device, dtype=torch.float32)
459
+ freqs = torch.outer(t, self.inv_freq)
460
+ emb = torch.cat((freqs, freqs), dim=-1)
461
+
462
+ # get attention temperature
463
+ temperature = self._get_temperature()
464
+
465
+ self.register_buffer("cos_cached", emb.cos() * temperature, persistent=False)
466
+ self.register_buffer("sin_cached", emb.sin() * temperature, persistent=False)
467
+ self.max_seq_len_cached = seq_len
468
+
469
+ def forward(self, q, k, position_ids):
470
+ seq_len = max(position_ids.max().item() + 1, k.shape[2])
471
+
472
+ # x: [bs, num_attention_heads, seq_len, head_size]
473
+ if seq_len > self.max_seq_len_cached:
474
+ self.scaling_factor = seq_len / self.max_position_embeddings
475
+ self._set_cos_sin_cache(seq_len=seq_len, device=k.device, dtype=k.dtype)
476
+
477
+ k_cos = self.cos_cached[position_ids].to(dtype=k.dtype).unsqueeze(1)
478
+ k_sin = self.sin_cached[position_ids].to(dtype=k.dtype).unsqueeze(1)
479
+
480
+ q_cos = k_cos[..., -q.shape[2]:, :]
481
+ q_sin = k_sin[..., -q.shape[2]:, :]
482
+
483
+ q_embed = (q * q_cos) + (rotate_half(q) * q_sin)
484
+ k_embed = (k * k_cos) + (rotate_half(k) * k_sin)
485
+ return q_embed, k_embed
486
+
487
+
488
+ class YarnDynamicTemperatureRotaryEmbedding(torch.nn.Module):
489
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0, beta_slow=2, beta_fast=128):
490
+ super().__init__()
491
+
492
+ self.base = base
493
+ self.dim = dim
494
+ self.scaling_factor = scaling_factor
495
+ self.beta_slow = beta_slow
496
+ self.beta_fast = beta_fast
497
+ self.max_position_embeddings = max_position_embeddings
498
+
499
+ self._set_cos_sin_cache(
500
+ seq_len=math.ceil(max_position_embeddings * scaling_factor), device=device, dtype=torch.get_default_dtype()
501
+ )
502
+
503
+ def _get_factor(self):
504
+ # the dimension whose index is smaller than fast_dim rotates more than beta_fast
505
+ fast_dim = self.dim / 2 * (math.log(self.max_position_embeddings / (2 * math.pi * self.beta_fast)) / math.log(self.base))
506
+ fast_dim = max(math.floor(fast_dim), 0)
507
+ # the dimension whose index is bigger than slow_dim rotates less than beta_slow
508
+ slow_dim = self.dim / 2 * (math.log(self.max_position_embeddings / (2 * math.pi * self.beta_slow)) / math.log(self.base))
509
+ slow_dim = min(math.ceil(slow_dim), self.dim - 1)
510
+
511
+ if fast_dim == slow_dim:
512
+ slow_dim += 0.001
513
+
514
+ # NOTE: very important to use full precision here so that the factor is correct
515
+ dim_arange = torch.arange(0, self.dim // 2, dtype=torch.float32)
516
+ dim_factor = (dim_arange - fast_dim) / (slow_dim - fast_dim)
517
+ dim_factor = torch.clamp(dim_factor, 0, 1)
518
+
519
+ # align with the paper notation
520
+ return (1 - dim_factor)
521
+
522
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
523
+ dim_arange = torch.arange(0, self.dim, 2, device=device, dtype=torch.float32) / self.dim
524
+ # dim / 2
525
+ freq = self.base ** dim_arange
526
+ theta = 1 / freq
527
+ interleave_theta = theta / self.scaling_factor
528
+
529
+ factor = self._get_factor().to(device)
530
+ yarn_theta = factor * theta + (1 - factor) * interleave_theta
531
+ self.register_buffer("inv_freq", yarn_theta, persistent=False)
532
+
533
+ positions = torch.arange(seq_len, device=device, dtype=torch.float32)
534
+ freqs = torch.outer(positions, self.inv_freq)
535
+ emb = torch.cat((freqs, freqs), dim=-1)
536
+
537
+ # NOTE: get attention temperature that will be applied on the query vector
538
+ # temperature = torch.log(positions + 1) / math.log(self.max_position_embeddings)
539
+ temperature = (0.07 * torch.log((positions + 1) / self.max_position_embeddings) + 1) ** 2
540
+ temperature[:self.max_position_embeddings] = 1
541
+ self.register_buffer("temperature", temperature.unsqueeze(1), persistent=False)
542
+
543
+ self.register_buffer("cos_cached", emb.cos(), persistent=False)
544
+ self.register_buffer("sin_cached", emb.sin(), persistent=False)
545
+ self.max_seq_len_cached = seq_len
546
+
547
+ def forward(self, q, k, position_ids):
548
+ seq_len = max(position_ids.max().item() + 1, k.shape[2])
549
+
550
+ # x: [bs, num_attention_heads, seq_len, head_size]
551
+ if seq_len > self.max_seq_len_cached:
552
+ self.scaling_factor = seq_len / self.max_position_embeddings
553
+ self._set_cos_sin_cache(seq_len=seq_len, device=k.device, dtype=k.dtype)
554
+
555
+ # batch_size, 1, key_len, head_dim
556
+ k_cos = self.cos_cached[position_ids].to(dtype=k.dtype).unsqueeze(1)
557
+ k_sin = self.sin_cached[position_ids].to(dtype=k.dtype).unsqueeze(1)
558
+
559
+ q_cos = k_cos[..., -q.shape[2]:, :]
560
+ q_sin = k_sin[..., -q.shape[2]:, :]
561
+
562
+ q_position_ids = position_ids[:, -q.shape[2]:]
563
+ temperature = self.temperature[q_position_ids].to(dtype=k.dtype).unsqueeze(1)
564
+ q_cos = q_cos * temperature
565
+ q_sin = q_sin * temperature
566
+
567
+ q_embed = (q * q_cos) + (rotate_half(q) * q_sin)
568
+ k_embed = (k * k_cos) + (rotate_half(k) * k_sin)
569
+ return q_embed, k_embed
570
+
571
+
572
+ class YarnDynamicTemperatureLogNRotaryEmbedding(torch.nn.Module):
573
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0, beta_slow=2, beta_fast=128):
574
+ super().__init__()
575
+
576
+ self.base = base
577
+ self.dim = dim
578
+ self.scaling_factor = scaling_factor
579
+ self.beta_slow = beta_slow
580
+ self.beta_fast = beta_fast
581
+ self.max_position_embeddings = max_position_embeddings
582
+
583
+ self._set_cos_sin_cache(
584
+ seq_len=math.ceil(max_position_embeddings * scaling_factor), device=device, dtype=torch.get_default_dtype()
585
+ )
586
+
587
+ def _get_factor(self):
588
+ # the dimension whose index is smaller than fast_dim rotates more than beta_fast
589
+ fast_dim = self.dim / 2 * (math.log(self.max_position_embeddings / (2 * math.pi * self.beta_fast)) / math.log(self.base))
590
+ fast_dim = max(math.floor(fast_dim), 0)
591
+ # the dimension whose index is bigger than slow_dim rotates less than beta_slow
592
+ slow_dim = self.dim / 2 * (math.log(self.max_position_embeddings / (2 * math.pi * self.beta_slow)) / math.log(self.base))
593
+ slow_dim = min(math.ceil(slow_dim), self.dim - 1)
594
+
595
+ if fast_dim == slow_dim:
596
+ slow_dim += 0.001
597
+
598
+ # NOTE: very important to use full precision here so that the factor is correct
599
+ dim_arange = torch.arange(0, self.dim // 2, dtype=torch.float32)
600
+ dim_factor = (dim_arange - fast_dim) / (slow_dim - fast_dim)
601
+ dim_factor = torch.clamp(dim_factor, 0, 1)
602
+
603
+ # align with the paper notation
604
+ return (1 - dim_factor)
605
+
606
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
607
+ dim_arange = torch.arange(0, self.dim, 2, device=device, dtype=torch.float32) / self.dim
608
+ # dim / 2
609
+ freq = self.base ** dim_arange
610
+ theta = 1 / freq
611
+ interleave_theta = theta / self.scaling_factor
612
+
613
+ factor = self._get_factor().to(device)
614
+ yarn_theta = factor * theta + (1 - factor) * interleave_theta
615
+ self.register_buffer("inv_freq", yarn_theta, persistent=False)
616
+
617
+ positions = torch.arange(seq_len, device=device, dtype=torch.float32)
618
+ freqs = torch.outer(positions, self.inv_freq)
619
+ emb = torch.cat((freqs, freqs), dim=-1)
620
+
621
+ # NOTE: get attention temperature that will be applied on the query vector
622
+ temperature = torch.log(positions + 1) / math.log(self.max_position_embeddings)
623
+ # temperature = (0.07 * torch.log((positions + 1) / self.max_position_embeddings) + 1) ** 2
624
+ temperature[:self.max_position_embeddings] = 1
625
+ self.register_buffer("temperature", temperature.unsqueeze(1), persistent=False)
626
+
627
+ self.register_buffer("cos_cached", emb.cos(), persistent=False)
628
+ self.register_buffer("sin_cached", emb.sin(), persistent=False)
629
+ self.max_seq_len_cached = seq_len
630
+
631
+ def forward(self, q, k, position_ids):
632
+ seq_len = max(position_ids.max().item() + 1, k.shape[2])
633
+
634
+ # x: [bs, num_attention_heads, seq_len, head_size]
635
+ if seq_len > self.max_seq_len_cached:
636
+ self.scaling_factor = seq_len / self.max_position_embeddings
637
+ self._set_cos_sin_cache(seq_len=seq_len, device=k.device, dtype=k.dtype)
638
+
639
+ # batch_size, 1, key_len, head_dim
640
+ k_cos = self.cos_cached[position_ids].to(dtype=k.dtype).unsqueeze(1)
641
+ k_sin = self.sin_cached[position_ids].to(dtype=k.dtype).unsqueeze(1)
642
+
643
+ q_cos = k_cos[..., -q.shape[2]:, :]
644
+ q_sin = k_sin[..., -q.shape[2]:, :]
645
+
646
+ q_position_ids = position_ids[:, -q.shape[2]:]
647
+ temperature = self.temperature[q_position_ids].to(dtype=k.dtype).unsqueeze(1)
648
+ q_cos = q_cos * temperature
649
+ q_sin = q_sin * temperature
650
+
651
+ q_embed = (q * q_cos) + (rotate_half(q) * q_sin)
652
+ k_embed = (k * k_cos) + (rotate_half(k) * k_sin)
653
+ return q_embed, k_embed
654
+
655
+
656
+ class Llama3RotaryEmbedding(torch.nn.Module):
657
+ def __init__(self, dim, max_position_embeddings=8192, base=10000, device=None, scaling_factor=1.0, original_max_position_embeddings=8192, low_freq_factor=1, high_freq_factor=4):
658
+ super().__init__()
659
+
660
+ self.base = base
661
+ self.dim = dim
662
+ self.scaling_factor = scaling_factor
663
+ self.original_max_position_embeddings = original_max_position_embeddings
664
+ self.max_position_embeddings = max(max_position_embeddings, int(original_max_position_embeddings * scaling_factor))
665
+ self.low_freq_factor = low_freq_factor
666
+ self.high_freq_factor = high_freq_factor
667
+
668
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.float32).to(device) / self.dim))
669
+ low_freq_wavelen = self.original_max_position_embeddings / low_freq_factor
670
+ high_freq_wavelen = self.original_max_position_embeddings / high_freq_factor
671
+ new_freqs = []
672
+ for freq in inv_freq:
673
+ wavelen = 2 * math.pi / freq
674
+ if wavelen < high_freq_wavelen:
675
+ new_freqs.append(freq)
676
+ elif wavelen > low_freq_wavelen:
677
+ new_freqs.append(freq / scaling_factor)
678
+ else:
679
+ assert low_freq_wavelen != high_freq_wavelen
680
+ smooth = (self.original_max_position_embeddings / wavelen - low_freq_factor) / (high_freq_factor - low_freq_factor)
681
+ new_freqs.append((1 - smooth) * freq / scaling_factor + smooth * freq)
682
+ inv_freq = torch.tensor(new_freqs, dtype=inv_freq.dtype, device=inv_freq.device)
683
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
684
+
685
+ self._set_cos_sin_cache(seq_len=self.max_position_embeddings, device=device)
686
+
687
+ def _set_cos_sin_cache(self, seq_len, device):
688
+ self.max_seq_len_cached = seq_len
689
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.float32)
690
+ freqs = torch.outer(t, self.inv_freq)
691
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
692
+ emb = torch.cat((freqs, freqs), dim=-1)
693
+ self.register_buffer("cos_cached", emb.cos(), persistent=False)
694
+ self.register_buffer("sin_cached", emb.sin(), persistent=False)
695
+
696
+ def forward(self, q, k, position_ids):
697
+ seq_len = max(position_ids.max().item() + 1, k.shape[2])
698
+
699
+ # x: [bs, num_attention_heads, seq_len, head_size]
700
+ if seq_len > self.max_seq_len_cached:
701
+ self._set_cos_sin_cache(seq_len=seq_len, device=k.device)
702
+
703
+ k_cos = self.cos_cached[position_ids].to(dtype=k.dtype).unsqueeze(1)
704
+ k_sin = self.sin_cached[position_ids].to(dtype=k.dtype).unsqueeze(1)
705
+
706
+ q_cos = k_cos[..., -q.shape[2]:, :]
707
+ q_sin = k_sin[..., -q.shape[2]:, :]
708
+
709
+ q_embed = (q * q_cos) + (rotate_half(q) * q_sin)
710
+ k_embed = (k * k_cos) + (rotate_half(k) * k_sin)
711
+ return q_embed, k_embed
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
+ }
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2033b811b3474a96f5c2c4757d753e269ed2ef5e1aef1faaf2fc55a9c4b32b06
3
+ size 7480
vocab.json ADDED
The diff for this file is too large to render. See raw diff