xingyusu commited on
Commit
0364666
·
verified ·
1 Parent(s): 0026f6b

Initial upload to divelab/OPDLM-0.6B

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
added_tokens.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</think>": 151668,
3
+ "</tool_call>": 151658,
4
+ "</tool_response>": 151666,
5
+ "<think>": 151667,
6
+ "<tool_call>": 151657,
7
+ "<tool_response>": 151665,
8
+ "<|MASK|>": 151669,
9
+ "<|box_end|>": 151649,
10
+ "<|box_start|>": 151648,
11
+ "<|endoftext|>": 151643,
12
+ "<|file_sep|>": 151664,
13
+ "<|fim_middle|>": 151660,
14
+ "<|fim_pad|>": 151662,
15
+ "<|fim_prefix|>": 151659,
16
+ "<|fim_suffix|>": 151661,
17
+ "<|im_end|>": 151645,
18
+ "<|im_start|>": 151644,
19
+ "<|image_pad|>": 151655,
20
+ "<|object_ref_end|>": 151647,
21
+ "<|object_ref_start|>": 151646,
22
+ "<|quad_end|>": 151651,
23
+ "<|quad_start|>": 151650,
24
+ "<|repo_name|>": 151663,
25
+ "<|video_pad|>": 151656,
26
+ "<|vision_end|>": 151653,
27
+ "<|vision_pad|>": 151654,
28
+ "<|vision_start|>": 151652
29
+ }
chat_template.jinja ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tools %}
2
+ {{- '<|im_start|>system\n' }}
3
+ {%- if messages[0].role == 'system' %}
4
+ {{- messages[0].content + '\n\n' }}
5
+ {%- endif %}
6
+ {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
7
+ {%- for tool in tools %}
8
+ {{- "\n" }}
9
+ {{- tool | tojson }}
10
+ {%- endfor %}
11
+ {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
12
+ {%- else %}
13
+ {%- if messages[0].role == 'system' %}
14
+ {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
15
+ {%- endif %}
16
+ {%- endif %}
17
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
18
+ {%- for message in messages[::-1] %}
19
+ {%- set index = (messages|length - 1) - loop.index0 %}
20
+ {%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}
21
+ {%- set ns.multi_step_tool = false %}
22
+ {%- set ns.last_query_index = index %}
23
+ {%- endif %}
24
+ {%- endfor %}
25
+ {%- for message in messages %}
26
+ {%- if message.content is string %}
27
+ {%- set content = message.content %}
28
+ {%- else %}
29
+ {%- set content = '' %}
30
+ {%- endif %}
31
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
32
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
33
+ {%- elif message.role == "assistant" %}
34
+ {%- set reasoning_content = '' %}
35
+ {%- if message.reasoning_content is string %}
36
+ {%- set reasoning_content = message.reasoning_content %}
37
+ {%- else %}
38
+ {%- if '</think>' in content %}
39
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
40
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
41
+ {%- endif %}
42
+ {%- endif %}
43
+ {%- if loop.index0 > ns.last_query_index %}
44
+ {%- if loop.last or (not loop.last and reasoning_content) %}
45
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
46
+ {%- else %}
47
+ {{- '<|im_start|>' + message.role + '\n' + content }}
48
+ {%- endif %}
49
+ {%- else %}
50
+ {{- '<|im_start|>' + message.role + '\n' + content }}
51
+ {%- endif %}
52
+ {%- if message.tool_calls %}
53
+ {%- for tool_call in message.tool_calls %}
54
+ {%- if (loop.first and content) or (not loop.first) %}
55
+ {{- '\n' }}
56
+ {%- endif %}
57
+ {%- if tool_call.function %}
58
+ {%- set tool_call = tool_call.function %}
59
+ {%- endif %}
60
+ {{- '<tool_call>\n{"name": "' }}
61
+ {{- tool_call.name }}
62
+ {{- '", "arguments": ' }}
63
+ {%- if tool_call.arguments is string %}
64
+ {{- tool_call.arguments }}
65
+ {%- else %}
66
+ {{- tool_call.arguments | tojson }}
67
+ {%- endif %}
68
+ {{- '}\n</tool_call>' }}
69
+ {%- endfor %}
70
+ {%- endif %}
71
+ {{- '<|im_end|>\n' }}
72
+ {%- elif message.role == "tool" %}
73
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
74
+ {{- '<|im_start|>user' }}
75
+ {%- endif %}
76
+ {{- '\n<tool_response>\n' }}
77
+ {{- content }}
78
+ {{- '\n</tool_response>' }}
79
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
80
+ {{- '<|im_end|>\n' }}
81
+ {%- endif %}
82
+ {%- endif %}
83
+ {%- endfor %}
84
+ {%- if add_generation_prompt %}
85
+ {{- '<|im_start|>assistant\n' }}
86
+ {%- if enable_thinking is defined and enable_thinking is false %}
87
+ {{- '<think>\n\n</think>\n\n' }}
88
+ {%- endif %}
89
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "_A2DQwen3LMHeadModel"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "bos_token_id": 151643,
8
+ "dtype": "bfloat16",
9
+ "eos_token_id": 151645,
10
+ "fuse_cross_entropy": false,
11
+ "head_dim": 128,
12
+ "hidden_act": "silu",
13
+ "hidden_size": 1024,
14
+ "initializer_range": 0.02,
15
+ "intermediate_size": 3072,
16
+ "layer_types": [
17
+ "full_attention",
18
+ "full_attention",
19
+ "full_attention",
20
+ "full_attention",
21
+ "full_attention",
22
+ "full_attention",
23
+ "full_attention",
24
+ "full_attention",
25
+ "full_attention",
26
+ "full_attention",
27
+ "full_attention",
28
+ "full_attention",
29
+ "full_attention",
30
+ "full_attention",
31
+ "full_attention",
32
+ "full_attention",
33
+ "full_attention",
34
+ "full_attention",
35
+ "full_attention",
36
+ "full_attention",
37
+ "full_attention",
38
+ "full_attention",
39
+ "full_attention",
40
+ "full_attention",
41
+ "full_attention",
42
+ "full_attention",
43
+ "full_attention",
44
+ "full_attention"
45
+ ],
46
+ "max_position_embeddings": 40960,
47
+ "max_window_layers": 28,
48
+ "model_type": "a2d-qwen3",
49
+ "num_attention_heads": 16,
50
+ "num_hidden_layers": 28,
51
+ "num_key_value_heads": 8,
52
+ "rms_norm_eps": 1e-06,
53
+ "rope_scaling": null,
54
+ "rope_theta": 1000000,
55
+ "sliding_window": null,
56
+ "tie_word_embeddings": true,
57
+ "torch_dtype": "bfloat16",
58
+ "transformers_version": "4.52.4",
59
+ "use_cache": false,
60
+ "use_sliding_window": false,
61
+ "vocab_size": 151936
62
+ }
configuration_qwen2.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ...configuration_utils import PretrainedConfig
18
+ from ...modeling_rope_utils import rope_config_validation
19
+ from ...utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class Qwen2Config(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`Qwen2Model`]. It is used to instantiate a
28
+ Qwen2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
29
+ with the defaults will yield a similar configuration to that of
30
+ Qwen2-7B-beta [Qwen/Qwen2-7B-beta](https://huggingface.co/Qwen/Qwen2-7B-beta).
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+
36
+ Args:
37
+ vocab_size (`int`, *optional*, defaults to 151936):
38
+ Vocabulary size of the Qwen2 model. Defines the number of different tokens that can be represented by the
39
+ `inputs_ids` passed when calling [`Qwen2Model`]
40
+ hidden_size (`int`, *optional*, defaults to 4096):
41
+ Dimension of the hidden representations.
42
+ intermediate_size (`int`, *optional*, defaults to 22016):
43
+ Dimension of the MLP representations.
44
+ num_hidden_layers (`int`, *optional*, defaults to 32):
45
+ Number of hidden layers in the Transformer encoder.
46
+ num_attention_heads (`int`, *optional*, defaults to 32):
47
+ Number of attention heads for each attention layer in the Transformer encoder.
48
+ num_key_value_heads (`int`, *optional*, defaults to 32):
49
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
50
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
51
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
52
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
53
+ by meanpooling all the original heads within that group. For more details checkout [this
54
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
55
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
56
+ The non-linear activation function (function or string) in the decoder.
57
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
58
+ The maximum sequence length that this model might ever be used with.
59
+ initializer_range (`float`, *optional*, defaults to 0.02):
60
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
61
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
62
+ The epsilon used by the rms normalization layers.
63
+ use_cache (`bool`, *optional*, defaults to `True`):
64
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
65
+ relevant if `config.is_decoder=True`.
66
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
67
+ Whether the model's input and output word embeddings should be tied.
68
+ rope_theta (`float`, *optional*, defaults to 10000.0):
69
+ The base period of the RoPE embeddings.
70
+ rope_scaling (`Dict`, *optional*):
71
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
72
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
73
+ accordingly.
74
+ Expected contents:
75
+ `rope_type` (`str`):
76
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
77
+ 'llama3'], with 'default' being the original RoPE implementation.
78
+ `factor` (`float`, *optional*):
79
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
80
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
81
+ original maximum pre-trained length.
82
+ `original_max_position_embeddings` (`int`, *optional*):
83
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
84
+ pretraining.
85
+ `attention_factor` (`float`, *optional*):
86
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
87
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
88
+ `factor` field to infer the suggested value.
89
+ `beta_fast` (`float`, *optional*):
90
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
91
+ ramp function. If unspecified, it defaults to 32.
92
+ `beta_slow` (`float`, *optional*):
93
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
94
+ ramp function. If unspecified, it defaults to 1.
95
+ `short_factor` (`List[float]`, *optional*):
96
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
97
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
98
+ size divided by the number of attention heads divided by 2
99
+ `long_factor` (`List[float]`, *optional*):
100
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
101
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
102
+ size divided by the number of attention heads divided by 2
103
+ `low_freq_factor` (`float`, *optional*):
104
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
105
+ `high_freq_factor` (`float`, *optional*):
106
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
107
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
108
+ Whether to use sliding window attention.
109
+ sliding_window (`int`, *optional*, defaults to 4096):
110
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
111
+ max_window_layers (`int`, *optional*, defaults to 28):
112
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
113
+ attention_dropout (`float`, *optional*, defaults to 0.0):
114
+ The dropout ratio for the attention probabilities.
115
+
116
+ ```python
117
+ >>> from transformers import Qwen2Model, Qwen2Config
118
+
119
+ >>> # Initializing a Qwen2 style configuration
120
+ >>> configuration = Qwen2Config()
121
+
122
+ >>> # Initializing a model from the Qwen2-7B style configuration
123
+ >>> model = Qwen2Model(configuration)
124
+
125
+ >>> # Accessing the model configuration
126
+ >>> configuration = model.config
127
+ ```"""
128
+
129
+ model_type = "qwen2"
130
+ keys_to_ignore_at_inference = ["past_key_values"]
131
+
132
+ # Default tensor parallel plan for base model `Qwen2`
133
+ base_model_tp_plan = {
134
+ "layers.*.self_attn.q_proj": "colwise",
135
+ "layers.*.self_attn.k_proj": "colwise",
136
+ "layers.*.self_attn.v_proj": "colwise",
137
+ "layers.*.self_attn.o_proj": "rowwise",
138
+ "layers.*.mlp.gate_proj": "colwise",
139
+ "layers.*.mlp.up_proj": "colwise",
140
+ "layers.*.mlp.down_proj": "rowwise",
141
+ }
142
+ base_model_pp_plan = {
143
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
144
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
145
+ "norm": (["hidden_states"], ["hidden_states"]),
146
+ }
147
+
148
+ def __init__(
149
+ self,
150
+ vocab_size=151936,
151
+ hidden_size=4096,
152
+ intermediate_size=22016,
153
+ num_hidden_layers=32,
154
+ num_attention_heads=32,
155
+ num_key_value_heads=32,
156
+ hidden_act="silu",
157
+ max_position_embeddings=32768,
158
+ initializer_range=0.02,
159
+ rms_norm_eps=1e-6,
160
+ use_cache=True,
161
+ tie_word_embeddings=False,
162
+ rope_theta=10000.0,
163
+ rope_scaling=None,
164
+ use_sliding_window=False,
165
+ sliding_window=4096,
166
+ max_window_layers=28,
167
+ attention_dropout=0.0,
168
+ **kwargs,
169
+ ):
170
+ self.vocab_size = vocab_size
171
+ self.max_position_embeddings = max_position_embeddings
172
+ self.hidden_size = hidden_size
173
+ self.intermediate_size = intermediate_size
174
+ self.num_hidden_layers = num_hidden_layers
175
+ self.num_attention_heads = num_attention_heads
176
+ self.use_sliding_window = use_sliding_window
177
+ self.sliding_window = sliding_window # we check `use_sliding_window` in the modeling code
178
+ self.max_window_layers = max_window_layers
179
+
180
+ # for backward compatibility
181
+ if num_key_value_heads is None:
182
+ num_key_value_heads = num_attention_heads
183
+
184
+ self.num_key_value_heads = num_key_value_heads
185
+ self.hidden_act = hidden_act
186
+ self.initializer_range = initializer_range
187
+ self.rms_norm_eps = rms_norm_eps
188
+ self.use_cache = use_cache
189
+ self.rope_theta = rope_theta
190
+ self.rope_scaling = rope_scaling
191
+ self.attention_dropout = attention_dropout
192
+ # Validate the correctness of rotary position embeddings parameters
193
+ # BC: if there is a 'type' field, move it to 'rope_type'.
194
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
195
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
196
+ rope_config_validation(self)
197
+
198
+ super().__init__(
199
+ tie_word_embeddings=tie_word_embeddings,
200
+ **kwargs,
201
+ )
202
+
203
+
204
+ __all__ = ["Qwen2Config"]
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 151643,
4
+ "eos_token_id": 151645,
5
+ "transformers_version": "4.52.4"
6
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b21185037fde14214e7473ac29632770592bcfd6f7f532d73c35ec2a9f5098a5
3
+ size 1192135096
modeling_qwen2.py ADDED
@@ -0,0 +1,975 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/qwen2/modular_qwen2.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_qwen2.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ from typing import Callable, Optional, Tuple, Union
8
+
9
+ import torch
10
+ from torch import nn
11
+
12
+ from ...activations import ACT2FN
13
+ from ...cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCache
14
+ from ...generation import GenerationMixin
15
+ from ...integrations import use_kernel_forward_from_hub
16
+ from ...modeling_attn_mask_utils import AttentionMaskConverter
17
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
18
+ from ...modeling_layers import GradientCheckpointingLayer
19
+ from ...modeling_outputs import (
20
+ BaseModelOutputWithPast,
21
+ CausalLMOutputWithPast,
22
+ QuestionAnsweringModelOutput,
23
+ SequenceClassifierOutputWithPast,
24
+ TokenClassifierOutput,
25
+ )
26
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
27
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
28
+ from ...processing_utils import Unpack
29
+ from ...utils import LossKwargs, auto_docstring, can_return_tuple, is_torch_flex_attn_available, logging
30
+ from .configuration_qwen2 import Qwen2Config
31
+
32
+
33
+ if is_torch_flex_attn_available():
34
+ from torch.nn.attention.flex_attention import BlockMask
35
+
36
+ from ...integrations.flex_attention import make_flex_block_causal_mask
37
+
38
+
39
+ logger = logging.get_logger(__name__)
40
+
41
+
42
+ class Qwen2MLP(nn.Module):
43
+ def __init__(self, config):
44
+ super().__init__()
45
+ self.config = config
46
+ self.hidden_size = config.hidden_size
47
+ self.intermediate_size = config.intermediate_size
48
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
49
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
50
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
51
+ self.act_fn = ACT2FN[config.hidden_act]
52
+
53
+ def forward(self, x):
54
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
55
+ return down_proj
56
+
57
+
58
+ def rotate_half(x):
59
+ """Rotates half the hidden dims of the input."""
60
+ x1 = x[..., : x.shape[-1] // 2]
61
+ x2 = x[..., x.shape[-1] // 2 :]
62
+ return torch.cat((-x2, x1), dim=-1)
63
+
64
+
65
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
66
+ """Applies Rotary Position Embedding to the query and key tensors.
67
+
68
+ Args:
69
+ q (`torch.Tensor`): The query tensor.
70
+ k (`torch.Tensor`): The key tensor.
71
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
72
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
73
+ position_ids (`torch.Tensor`, *optional*):
74
+ Deprecated and unused.
75
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
76
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
77
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
78
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
79
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
80
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
81
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
82
+ Returns:
83
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
84
+ """
85
+ cos = cos.unsqueeze(unsqueeze_dim)
86
+ sin = sin.unsqueeze(unsqueeze_dim)
87
+ q_embed = (q * cos) + (rotate_half(q) * sin)
88
+ k_embed = (k * cos) + (rotate_half(k) * sin)
89
+ return q_embed, k_embed
90
+
91
+
92
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
93
+ """
94
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
95
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
96
+ """
97
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
98
+ if n_rep == 1:
99
+ return hidden_states
100
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
101
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
102
+
103
+
104
+ def eager_attention_forward(
105
+ module: nn.Module,
106
+ query: torch.Tensor,
107
+ key: torch.Tensor,
108
+ value: torch.Tensor,
109
+ attention_mask: Optional[torch.Tensor],
110
+ scaling: float,
111
+ dropout: float = 0.0,
112
+ **kwargs,
113
+ ):
114
+ key_states = repeat_kv(key, module.num_key_value_groups)
115
+ value_states = repeat_kv(value, module.num_key_value_groups)
116
+
117
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
118
+ if attention_mask is not None:
119
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
120
+ attn_weights = attn_weights + causal_mask
121
+
122
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
123
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
124
+ attn_output = torch.matmul(attn_weights, value_states)
125
+ attn_output = attn_output.transpose(1, 2).contiguous()
126
+
127
+ return attn_output, attn_weights
128
+
129
+
130
+ class Qwen2Attention(nn.Module):
131
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
132
+
133
+ def __init__(self, config: Qwen2Config, layer_idx: int):
134
+ super().__init__()
135
+ self.config = config
136
+ self.layer_idx = layer_idx
137
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
138
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
139
+ self.scaling = self.head_dim**-0.5
140
+ self.attention_dropout = config.attention_dropout
141
+ self.is_causal = True
142
+ self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=True)
143
+ self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
144
+ self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
145
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
146
+
147
+ def forward(
148
+ self,
149
+ hidden_states: torch.Tensor,
150
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
151
+ attention_mask: Optional[torch.Tensor],
152
+ past_key_value: Optional[Cache] = None,
153
+ cache_position: Optional[torch.LongTensor] = None,
154
+ **kwargs: Unpack[FlashAttentionKwargs],
155
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
156
+ input_shape = hidden_states.shape[:-1]
157
+ hidden_shape = (*input_shape, -1, self.head_dim)
158
+
159
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
160
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
161
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
162
+
163
+ cos, sin = position_embeddings
164
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
165
+
166
+ if past_key_value is not None:
167
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
168
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
169
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
170
+
171
+ sliding_window = None
172
+ if (
173
+ self.config.use_sliding_window
174
+ and getattr(self.config, "sliding_window", None) is not None
175
+ and self.layer_idx >= self.config.max_window_layers
176
+ ):
177
+ sliding_window = self.config.sliding_window
178
+
179
+ attention_interface: Callable = eager_attention_forward
180
+ if self.config._attn_implementation != "eager":
181
+ if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
182
+ logger.warning_once(
183
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
184
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
185
+ )
186
+ else:
187
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
188
+
189
+ attn_output, attn_weights = attention_interface(
190
+ self,
191
+ query_states,
192
+ key_states,
193
+ value_states,
194
+ attention_mask,
195
+ dropout=0.0 if not self.training else self.attention_dropout,
196
+ scaling=self.scaling,
197
+ sliding_window=sliding_window, # main diff with Llama
198
+ **kwargs,
199
+ )
200
+
201
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
202
+ attn_output = self.o_proj(attn_output)
203
+ return attn_output, attn_weights
204
+
205
+
206
+ @use_kernel_forward_from_hub("RMSNorm")
207
+ class Qwen2RMSNorm(nn.Module):
208
+ def __init__(self, hidden_size, eps=1e-6):
209
+ """
210
+ Qwen2RMSNorm is equivalent to T5LayerNorm
211
+ """
212
+ super().__init__()
213
+ self.weight = nn.Parameter(torch.ones(hidden_size))
214
+ self.variance_epsilon = eps
215
+
216
+ def forward(self, hidden_states):
217
+ input_dtype = hidden_states.dtype
218
+ hidden_states = hidden_states.to(torch.float32)
219
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
220
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
221
+ return self.weight * hidden_states.to(input_dtype)
222
+
223
+ def extra_repr(self):
224
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
225
+
226
+
227
+ class Qwen2DecoderLayer(GradientCheckpointingLayer):
228
+ def __init__(self, config: Qwen2Config, layer_idx: int):
229
+ super().__init__()
230
+ self.hidden_size = config.hidden_size
231
+ self.self_attn = Qwen2Attention(config=config, layer_idx=layer_idx)
232
+ self.mlp = Qwen2MLP(config)
233
+ self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
234
+ self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
235
+ if config.use_sliding_window and config._attn_implementation != "flash_attention_2":
236
+ logger.warning_once(
237
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
238
+ "unexpected results may be encountered."
239
+ )
240
+
241
+ def forward(
242
+ self,
243
+ hidden_states: torch.Tensor,
244
+ attention_mask: Optional[torch.Tensor] = None,
245
+ position_ids: Optional[torch.LongTensor] = None,
246
+ past_key_value: Optional[Cache] = None,
247
+ output_attentions: Optional[bool] = False,
248
+ use_cache: Optional[bool] = False,
249
+ cache_position: Optional[torch.LongTensor] = None,
250
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
251
+ **kwargs: Unpack[FlashAttentionKwargs],
252
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
253
+ residual = hidden_states
254
+ hidden_states = self.input_layernorm(hidden_states)
255
+
256
+ # Self Attention
257
+ hidden_states, self_attn_weights = self.self_attn(
258
+ hidden_states=hidden_states,
259
+ attention_mask=attention_mask,
260
+ position_ids=position_ids,
261
+ past_key_value=past_key_value,
262
+ output_attentions=output_attentions,
263
+ use_cache=use_cache,
264
+ cache_position=cache_position,
265
+ position_embeddings=position_embeddings,
266
+ **kwargs,
267
+ )
268
+ hidden_states = residual + hidden_states
269
+
270
+ # Fully Connected
271
+ residual = hidden_states
272
+ hidden_states = self.post_attention_layernorm(hidden_states)
273
+ hidden_states = self.mlp(hidden_states)
274
+ hidden_states = residual + hidden_states
275
+
276
+ outputs = (hidden_states,)
277
+ if output_attentions:
278
+ outputs += (self_attn_weights,)
279
+
280
+ return outputs
281
+
282
+
283
+ @auto_docstring
284
+ class Qwen2PreTrainedModel(PreTrainedModel):
285
+ config_class = Qwen2Config
286
+ base_model_prefix = "model"
287
+ supports_gradient_checkpointing = True
288
+ _no_split_modules = ["Qwen2DecoderLayer"]
289
+ _skip_keys_device_placement = ["past_key_values"]
290
+ _supports_flash_attn_2 = True
291
+ _supports_sdpa = True
292
+ _supports_flex_attn = True
293
+ _supports_cache_class = True
294
+ _supports_quantized_cache = True
295
+ _supports_static_cache = True
296
+ _supports_attention_backend = True
297
+
298
+ def _init_weights(self, module):
299
+ std = self.config.initializer_range
300
+ if isinstance(module, nn.Linear):
301
+ module.weight.data.normal_(mean=0.0, std=std)
302
+ if module.bias is not None:
303
+ module.bias.data.zero_()
304
+ elif isinstance(module, nn.Embedding):
305
+ module.weight.data.normal_(mean=0.0, std=std)
306
+ if module.padding_idx is not None:
307
+ module.weight.data[module.padding_idx].zero_()
308
+ elif isinstance(module, Qwen2RMSNorm):
309
+ module.weight.data.fill_(1.0)
310
+
311
+
312
+ class Qwen2RotaryEmbedding(nn.Module):
313
+ def __init__(self, config: Qwen2Config, device=None):
314
+ super().__init__()
315
+ # BC: "rope_type" was originally "type"
316
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
317
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
318
+ else:
319
+ self.rope_type = "default"
320
+ self.max_seq_len_cached = config.max_position_embeddings
321
+ self.original_max_seq_len = config.max_position_embeddings
322
+
323
+ self.config = config
324
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
325
+
326
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
327
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
328
+ self.original_inv_freq = self.inv_freq
329
+
330
+ @torch.no_grad()
331
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
332
+ def forward(self, x, position_ids):
333
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
334
+ position_ids_expanded = position_ids[:, None, :].float()
335
+
336
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
337
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
338
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
339
+ emb = torch.cat((freqs, freqs), dim=-1)
340
+ cos = emb.cos() * self.attention_scaling
341
+ sin = emb.sin() * self.attention_scaling
342
+
343
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
344
+
345
+
346
+ @auto_docstring
347
+ class Qwen2Model(Qwen2PreTrainedModel):
348
+ def __init__(self, config: Qwen2Config):
349
+ super().__init__(config)
350
+ self.padding_idx = config.pad_token_id
351
+ self.vocab_size = config.vocab_size
352
+
353
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
354
+ self.layers = nn.ModuleList(
355
+ [Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
356
+ )
357
+ self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
358
+ self.rotary_emb = Qwen2RotaryEmbedding(config=config)
359
+ self.gradient_checkpointing = False
360
+
361
+ # Initialize weights and apply final processing
362
+ self.post_init()
363
+
364
+ def get_input_embeddings(self):
365
+ return self.embed_tokens
366
+
367
+ def set_input_embeddings(self, value):
368
+ self.embed_tokens = value
369
+
370
+ @can_return_tuple
371
+ @auto_docstring
372
+ def forward(
373
+ self,
374
+ input_ids: Optional[torch.LongTensor] = None,
375
+ attention_mask: Optional[torch.Tensor] = None,
376
+ position_ids: Optional[torch.LongTensor] = None,
377
+ past_key_values: Optional[Cache] = None,
378
+ inputs_embeds: Optional[torch.FloatTensor] = None,
379
+ use_cache: Optional[bool] = None,
380
+ output_attentions: Optional[bool] = None,
381
+ output_hidden_states: Optional[bool] = None,
382
+ cache_position: Optional[torch.LongTensor] = None,
383
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
384
+ ) -> BaseModelOutputWithPast:
385
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
386
+ output_hidden_states = (
387
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
388
+ )
389
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
390
+
391
+ if (input_ids is None) ^ (inputs_embeds is not None):
392
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
393
+
394
+ if self.gradient_checkpointing and self.training and use_cache:
395
+ logger.warning_once(
396
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
397
+ )
398
+ use_cache = False
399
+
400
+ # TODO (joao): remove this exception in v4.56 -- it exists for users that try to pass a legacy cache
401
+ if not isinstance(past_key_values, (type(None), Cache)):
402
+ raise ValueError("The `past_key_values` should be either a `Cache` object or `None`.")
403
+
404
+ if inputs_embeds is None:
405
+ inputs_embeds = self.embed_tokens(input_ids)
406
+
407
+ if use_cache and past_key_values is None:
408
+ past_key_values = DynamicCache()
409
+
410
+ if cache_position is None:
411
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
412
+ cache_position = torch.arange(
413
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
414
+ )
415
+
416
+ if position_ids is None:
417
+ position_ids = cache_position.unsqueeze(0)
418
+
419
+ causal_mask = self._update_causal_mask(
420
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
421
+ )
422
+
423
+ hidden_states = inputs_embeds
424
+
425
+ # create position embeddings to be shared across the decoder layers
426
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
427
+
428
+ # decoder layers
429
+ all_hidden_states = () if output_hidden_states else None
430
+ all_self_attns = () if output_attentions else None
431
+
432
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
433
+ if output_hidden_states:
434
+ all_hidden_states += (hidden_states,)
435
+
436
+ layer_outputs = decoder_layer(
437
+ hidden_states,
438
+ attention_mask=causal_mask,
439
+ position_ids=position_ids,
440
+ past_key_value=past_key_values,
441
+ output_attentions=output_attentions,
442
+ use_cache=use_cache,
443
+ cache_position=cache_position,
444
+ position_embeddings=position_embeddings,
445
+ **flash_attn_kwargs,
446
+ )
447
+
448
+ hidden_states = layer_outputs[0]
449
+
450
+ if output_attentions:
451
+ all_self_attns += (layer_outputs[1],)
452
+
453
+ hidden_states = self.norm(hidden_states)
454
+
455
+ # add hidden states from the last decoder layer
456
+ if output_hidden_states:
457
+ all_hidden_states += (hidden_states,)
458
+
459
+ return BaseModelOutputWithPast(
460
+ last_hidden_state=hidden_states,
461
+ past_key_values=past_key_values if use_cache else None,
462
+ hidden_states=all_hidden_states,
463
+ attentions=all_self_attns,
464
+ )
465
+
466
+ def _update_causal_mask(
467
+ self,
468
+ attention_mask: Union[torch.Tensor, "BlockMask"],
469
+ input_tensor: torch.Tensor,
470
+ cache_position: torch.Tensor,
471
+ past_key_values: Cache,
472
+ output_attentions: bool = False,
473
+ ):
474
+ if self.config._attn_implementation == "flash_attention_2":
475
+ if attention_mask is not None and past_key_values is not None:
476
+ is_padding_right = attention_mask[:, -1].sum().item() != input_tensor.size()[0]
477
+ if is_padding_right:
478
+ raise ValueError(
479
+ "You are attempting to perform batched generation with padding_side='right'"
480
+ " this may lead to unexpected behaviour for Flash Attention version of Qwen2. Make sure to "
481
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
482
+ )
483
+ if attention_mask is not None and 0.0 in attention_mask:
484
+ return attention_mask
485
+ return None
486
+ if self.config._attn_implementation == "flex_attention":
487
+ if isinstance(attention_mask, torch.Tensor):
488
+ attention_mask = make_flex_block_causal_mask(attention_mask)
489
+ return attention_mask
490
+
491
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
492
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
493
+ # to infer the attention mask.
494
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
495
+ using_static_cache = isinstance(past_key_values, StaticCache)
496
+ using_sliding_window_cache = isinstance(past_key_values, SlidingWindowCache)
497
+
498
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
499
+ if (
500
+ self.config._attn_implementation == "sdpa"
501
+ and not (using_static_cache or using_sliding_window_cache)
502
+ and not output_attentions
503
+ ):
504
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
505
+ attention_mask,
506
+ inputs_embeds=input_tensor,
507
+ past_key_values_length=past_seen_tokens,
508
+ sliding_window=self.config.sliding_window,
509
+ is_training=self.training,
510
+ ):
511
+ return None
512
+
513
+ dtype = input_tensor.dtype
514
+ min_dtype = torch.finfo(dtype).min
515
+ sequence_length = input_tensor.shape[1]
516
+ # SlidingWindowCache or StaticCache
517
+ if using_sliding_window_cache or using_static_cache:
518
+ target_length = past_key_values.get_max_cache_shape()
519
+ # DynamicCache or no cache
520
+ else:
521
+ target_length = (
522
+ attention_mask.shape[-1]
523
+ if isinstance(attention_mask, torch.Tensor)
524
+ else past_seen_tokens + sequence_length + 1
525
+ )
526
+
527
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
528
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
529
+ attention_mask,
530
+ sequence_length=sequence_length,
531
+ target_length=target_length,
532
+ dtype=dtype,
533
+ cache_position=cache_position,
534
+ batch_size=input_tensor.shape[0],
535
+ config=self.config,
536
+ past_key_values=past_key_values,
537
+ )
538
+
539
+ if (
540
+ self.config._attn_implementation == "sdpa"
541
+ and attention_mask is not None
542
+ and attention_mask.device.type in ["cuda", "xpu", "npu"]
543
+ and not output_attentions
544
+ ):
545
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
546
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
547
+ # Details: https://github.com/pytorch/pytorch/issues/110213
548
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
549
+
550
+ return causal_mask
551
+
552
+ @staticmethod
553
+ def _prepare_4d_causal_attention_mask_with_cache_position(
554
+ attention_mask: torch.Tensor,
555
+ sequence_length: int,
556
+ target_length: int,
557
+ dtype: torch.dtype,
558
+ cache_position: torch.Tensor,
559
+ batch_size: int,
560
+ config: Qwen2Config,
561
+ past_key_values: Cache,
562
+ ):
563
+ """
564
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
565
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
566
+
567
+ Args:
568
+ attention_mask (`torch.Tensor`):
569
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
570
+ sequence_length (`int`):
571
+ The sequence length being processed.
572
+ target_length (`int`):
573
+ The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
574
+ dtype (`torch.dtype`):
575
+ The dtype to use for the 4D attention mask.
576
+ cache_position (`torch.Tensor`):
577
+ Indices depicting the position of the input sequence tokens in the sequence.
578
+ batch_size (`torch.Tensor`):
579
+ Batch size.
580
+ config (`Qwen2Config`):
581
+ The model's configuration class
582
+ past_key_values (`Cache`):
583
+ The cache class that is being used currently to generate
584
+ """
585
+ if attention_mask is not None and attention_mask.dim() == 4:
586
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
587
+ causal_mask = attention_mask
588
+ else:
589
+ min_dtype = torch.finfo(dtype).min
590
+ causal_mask = torch.full(
591
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device
592
+ )
593
+ diagonal_attend_mask = torch.arange(target_length, device=cache_position.device) > cache_position.reshape(
594
+ -1, 1
595
+ )
596
+ text_config = config.get_text_config()
597
+ if getattr(text_config, "use_sliding_window", True) and text_config.sliding_window is not None:
598
+ # if we have sliding window, we should not attend to tokens beyond sliding window length, so we mask them out also
599
+ # the check is needed to verify is current checkpoint was trained with sliding window or not
600
+ if not isinstance(past_key_values, SlidingWindowCache) or sequence_length > target_length:
601
+ sliding_attend_mask = torch.arange(target_length, device=cache_position.device) <= (
602
+ cache_position.reshape(-1, 1) - text_config.sliding_window
603
+ )
604
+ diagonal_attend_mask.bitwise_or_(sliding_attend_mask)
605
+ causal_mask *= diagonal_attend_mask
606
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
607
+ if attention_mask is not None:
608
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
609
+ if attention_mask.shape[-1] > target_length:
610
+ attention_mask = attention_mask[:, :target_length]
611
+ mask_length = attention_mask.shape[-1]
612
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
613
+ causal_mask.device
614
+ )
615
+ padding_mask = padding_mask == 0
616
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
617
+ padding_mask, min_dtype
618
+ )
619
+ return causal_mask
620
+
621
+
622
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
623
+
624
+
625
+ @auto_docstring
626
+ class Qwen2ForCausalLM(Qwen2PreTrainedModel, GenerationMixin):
627
+ _tied_weights_keys = ["lm_head.weight"]
628
+ _tp_plan = {"lm_head": "colwise_rep"}
629
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
630
+
631
+ def __init__(self, config):
632
+ super().__init__(config)
633
+ self.model = Qwen2Model(config)
634
+ self.vocab_size = config.vocab_size
635
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
636
+
637
+ # Initialize weights and apply final processing
638
+ self.post_init()
639
+
640
+ def get_input_embeddings(self):
641
+ return self.model.embed_tokens
642
+
643
+ def set_input_embeddings(self, value):
644
+ self.model.embed_tokens = value
645
+
646
+ def get_output_embeddings(self):
647
+ return self.lm_head
648
+
649
+ def set_output_embeddings(self, new_embeddings):
650
+ self.lm_head = new_embeddings
651
+
652
+ def set_decoder(self, decoder):
653
+ self.model = decoder
654
+
655
+ def get_decoder(self):
656
+ return self.model
657
+
658
+ @can_return_tuple
659
+ @auto_docstring
660
+ def forward(
661
+ self,
662
+ input_ids: Optional[torch.LongTensor] = None,
663
+ attention_mask: Optional[torch.Tensor] = None,
664
+ position_ids: Optional[torch.LongTensor] = None,
665
+ past_key_values: Optional[Cache] = None,
666
+ inputs_embeds: Optional[torch.FloatTensor] = None,
667
+ labels: Optional[torch.LongTensor] = None,
668
+ use_cache: Optional[bool] = None,
669
+ output_attentions: Optional[bool] = None,
670
+ output_hidden_states: Optional[bool] = None,
671
+ cache_position: Optional[torch.LongTensor] = None,
672
+ logits_to_keep: Union[int, torch.Tensor] = 0,
673
+ **kwargs: Unpack[KwargsForCausalLM],
674
+ ) -> CausalLMOutputWithPast:
675
+ r"""
676
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
677
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
678
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
679
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
680
+
681
+ Example:
682
+
683
+ ```python
684
+ >>> from transformers import AutoTokenizer, Qwen2ForCausalLM
685
+
686
+ >>> model = Qwen2ForCausalLM.from_pretrained("meta-qwen2/Qwen2-2-7b-hf")
687
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-qwen2/Qwen2-2-7b-hf")
688
+
689
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
690
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
691
+
692
+ >>> # Generate
693
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
694
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
695
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
696
+ ```"""
697
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
698
+ output_hidden_states = (
699
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
700
+ )
701
+
702
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
703
+ outputs: BaseModelOutputWithPast = self.model(
704
+ input_ids=input_ids,
705
+ attention_mask=attention_mask,
706
+ position_ids=position_ids,
707
+ past_key_values=past_key_values,
708
+ inputs_embeds=inputs_embeds,
709
+ use_cache=use_cache,
710
+ output_attentions=output_attentions,
711
+ output_hidden_states=output_hidden_states,
712
+ cache_position=cache_position,
713
+ **kwargs,
714
+ )
715
+
716
+ hidden_states = outputs.last_hidden_state
717
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
718
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
719
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
720
+
721
+ loss = None
722
+ if labels is not None:
723
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
724
+
725
+ return CausalLMOutputWithPast(
726
+ loss=loss,
727
+ logits=logits,
728
+ past_key_values=outputs.past_key_values,
729
+ hidden_states=outputs.hidden_states,
730
+ attentions=outputs.attentions,
731
+ )
732
+
733
+
734
+ @auto_docstring(
735
+ custom_intro="""
736
+ The Qwen2 Model transformer with a sequence classification head on top (linear layer).
737
+
738
+ [`Qwen2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
739
+ (e.g. GPT-2) do.
740
+
741
+ Since it does classification on the last token, it requires to know the position of the last token. If a
742
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
743
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
744
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
745
+ each row of the batch).
746
+ """
747
+ )
748
+ class Qwen2ForSequenceClassification(Qwen2PreTrainedModel):
749
+ def __init__(self, config):
750
+ super().__init__(config)
751
+ self.num_labels = config.num_labels
752
+ self.model = Qwen2Model(config)
753
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
754
+
755
+ # Initialize weights and apply final processing
756
+ self.post_init()
757
+
758
+ def get_input_embeddings(self):
759
+ return self.model.embed_tokens
760
+
761
+ def set_input_embeddings(self, value):
762
+ self.model.embed_tokens = value
763
+
764
+ @can_return_tuple
765
+ @auto_docstring
766
+ def forward(
767
+ self,
768
+ input_ids: Optional[torch.LongTensor] = None,
769
+ attention_mask: Optional[torch.Tensor] = None,
770
+ position_ids: Optional[torch.LongTensor] = None,
771
+ past_key_values: Optional[Cache] = None,
772
+ inputs_embeds: Optional[torch.FloatTensor] = None,
773
+ labels: Optional[torch.LongTensor] = None,
774
+ use_cache: Optional[bool] = None,
775
+ output_attentions: Optional[bool] = None,
776
+ output_hidden_states: Optional[bool] = None,
777
+ ) -> SequenceClassifierOutputWithPast:
778
+ r"""
779
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
780
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
781
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
782
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
783
+ """
784
+
785
+ transformer_outputs: BaseModelOutputWithPast = self.model(
786
+ input_ids,
787
+ attention_mask=attention_mask,
788
+ position_ids=position_ids,
789
+ past_key_values=past_key_values,
790
+ inputs_embeds=inputs_embeds,
791
+ use_cache=use_cache,
792
+ output_attentions=output_attentions,
793
+ output_hidden_states=output_hidden_states,
794
+ )
795
+ hidden_states = transformer_outputs.last_hidden_state
796
+ logits = self.score(hidden_states)
797
+
798
+ if input_ids is not None:
799
+ batch_size = input_ids.shape[0]
800
+ else:
801
+ batch_size = inputs_embeds.shape[0]
802
+
803
+ if self.config.pad_token_id is None and batch_size != 1:
804
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
805
+ if self.config.pad_token_id is None:
806
+ last_non_pad_token = -1
807
+ elif input_ids is not None:
808
+ # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
809
+ non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
810
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
811
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
812
+ else:
813
+ last_non_pad_token = -1
814
+ logger.warning_once(
815
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
816
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
817
+ )
818
+
819
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
820
+
821
+ loss = None
822
+ if labels is not None:
823
+ loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
824
+
825
+ return SequenceClassifierOutputWithPast(
826
+ loss=loss,
827
+ logits=pooled_logits,
828
+ past_key_values=transformer_outputs.past_key_values,
829
+ hidden_states=transformer_outputs.hidden_states,
830
+ attentions=transformer_outputs.attentions,
831
+ )
832
+
833
+
834
+ @auto_docstring
835
+ class Qwen2ForTokenClassification(Qwen2PreTrainedModel):
836
+ def __init__(self, config):
837
+ super().__init__(config)
838
+ self.num_labels = config.num_labels
839
+ self.model = Qwen2Model(config)
840
+ if getattr(config, "classifier_dropout", None) is not None:
841
+ classifier_dropout = config.classifier_dropout
842
+ elif getattr(config, "hidden_dropout", None) is not None:
843
+ classifier_dropout = config.hidden_dropout
844
+ else:
845
+ classifier_dropout = 0.1
846
+ self.dropout = nn.Dropout(classifier_dropout)
847
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
848
+
849
+ # Initialize weights and apply final processing
850
+ self.post_init()
851
+
852
+ def get_input_embeddings(self):
853
+ return self.model.embed_tokens
854
+
855
+ def set_input_embeddings(self, value):
856
+ self.model.embed_tokens = value
857
+
858
+ @can_return_tuple
859
+ @auto_docstring
860
+ def forward(
861
+ self,
862
+ input_ids: Optional[torch.LongTensor] = None,
863
+ attention_mask: Optional[torch.Tensor] = None,
864
+ position_ids: Optional[torch.LongTensor] = None,
865
+ past_key_values: Optional[Cache] = None,
866
+ inputs_embeds: Optional[torch.FloatTensor] = None,
867
+ labels: Optional[torch.LongTensor] = None,
868
+ use_cache: Optional[bool] = None,
869
+ output_attentions: Optional[bool] = None,
870
+ output_hidden_states: Optional[bool] = None,
871
+ ) -> TokenClassifierOutput:
872
+ r"""
873
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
874
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
875
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
876
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
877
+ """
878
+
879
+ outputs: BaseModelOutputWithPast = self.model(
880
+ input_ids,
881
+ attention_mask=attention_mask,
882
+ position_ids=position_ids,
883
+ past_key_values=past_key_values,
884
+ inputs_embeds=inputs_embeds,
885
+ use_cache=use_cache,
886
+ output_attentions=output_attentions,
887
+ output_hidden_states=output_hidden_states,
888
+ )
889
+ sequence_output = outputs.last_hidden_state
890
+ sequence_output = self.dropout(sequence_output)
891
+ logits = self.score(sequence_output)
892
+
893
+ loss = None
894
+ if labels is not None:
895
+ loss = self.loss_function(logits, labels, self.config)
896
+
897
+ return TokenClassifierOutput(
898
+ loss=loss,
899
+ logits=logits,
900
+ hidden_states=outputs.hidden_states,
901
+ attentions=outputs.attentions,
902
+ )
903
+
904
+
905
+ @auto_docstring
906
+ class Qwen2ForQuestionAnswering(Qwen2PreTrainedModel):
907
+ base_model_prefix = "transformer"
908
+
909
+ def __init__(self, config):
910
+ super().__init__(config)
911
+ self.transformer = Qwen2Model(config)
912
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
913
+
914
+ # Initialize weights and apply final processing
915
+ self.post_init()
916
+
917
+ def get_input_embeddings(self):
918
+ return self.transformer.embed_tokens
919
+
920
+ def set_input_embeddings(self, value):
921
+ self.transformer.embed_tokens = value
922
+
923
+ @can_return_tuple
924
+ @auto_docstring
925
+ def forward(
926
+ self,
927
+ input_ids: Optional[torch.LongTensor] = None,
928
+ attention_mask: Optional[torch.Tensor] = None,
929
+ position_ids: Optional[torch.LongTensor] = None,
930
+ past_key_values: Optional[Cache] = None,
931
+ inputs_embeds: Optional[torch.FloatTensor] = None,
932
+ start_positions: Optional[torch.LongTensor] = None,
933
+ end_positions: Optional[torch.LongTensor] = None,
934
+ output_attentions: Optional[bool] = None,
935
+ output_hidden_states: Optional[bool] = None,
936
+ **kwargs,
937
+ ) -> QuestionAnsweringModelOutput:
938
+ outputs: BaseModelOutputWithPast = self.transformer(
939
+ input_ids,
940
+ attention_mask=attention_mask,
941
+ position_ids=position_ids,
942
+ past_key_values=past_key_values,
943
+ inputs_embeds=inputs_embeds,
944
+ output_attentions=output_attentions,
945
+ output_hidden_states=output_hidden_states,
946
+ )
947
+
948
+ sequence_output = outputs.last_hidden_state
949
+
950
+ logits = self.qa_outputs(sequence_output)
951
+ start_logits, end_logits = logits.split(1, dim=-1)
952
+ start_logits = start_logits.squeeze(-1).contiguous()
953
+ end_logits = end_logits.squeeze(-1).contiguous()
954
+
955
+ loss = None
956
+ if start_positions is not None and end_positions is not None:
957
+ loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
958
+
959
+ return QuestionAnsweringModelOutput(
960
+ loss=loss,
961
+ start_logits=start_logits,
962
+ end_logits=end_logits,
963
+ hidden_states=outputs.hidden_states,
964
+ attentions=outputs.attentions,
965
+ )
966
+
967
+
968
+ __all__ = [
969
+ "Qwen2PreTrainedModel",
970
+ "Qwen2Model",
971
+ "Qwen2ForCausalLM",
972
+ "Qwen2ForSequenceClassification",
973
+ "Qwen2ForTokenClassification",
974
+ "Qwen2ForQuestionAnswering",
975
+ ]
special_tokens_map.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|object_ref_start|>",
6
+ "<|object_ref_end|>",
7
+ "<|box_start|>",
8
+ "<|box_end|>",
9
+ "<|quad_start|>",
10
+ "<|quad_end|>",
11
+ "<|vision_start|>",
12
+ "<|vision_end|>",
13
+ "<|vision_pad|>",
14
+ "<|image_pad|>",
15
+ "<|video_pad|>"
16
+ ],
17
+ "eos_token": {
18
+ "content": "<|im_end|>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ "mask_token": {
25
+ "content": "<|MASK|>",
26
+ "lstrip": false,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ },
31
+ "pad_token": {
32
+ "content": "<|endoftext|>",
33
+ "lstrip": false,
34
+ "normalized": false,
35
+ "rstrip": false,
36
+ "single_word": false
37
+ }
38
+ }
tokenization_qwen2.py ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Tokenization classes for Qwen2."""
16
+
17
+ import json
18
+ import os
19
+ import unicodedata
20
+ from functools import lru_cache
21
+ from typing import Optional, Tuple
22
+
23
+ import regex as re
24
+
25
+ from ...tokenization_utils import AddedToken, PreTrainedTokenizer
26
+ from ...utils import logging
27
+
28
+
29
+ logger = logging.get_logger(__name__)
30
+
31
+ VOCAB_FILES_NAMES = {
32
+ "vocab_file": "vocab.json",
33
+ "merges_file": "merges.txt",
34
+ }
35
+
36
+
37
+ MAX_MODEL_INPUT_SIZES = {"qwen/qwen-tokenizer": 32768}
38
+
39
+ PRETOKENIZE_REGEX = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
40
+
41
+
42
+ @lru_cache()
43
+ # Copied from transformers.models.gpt2.tokenization_gpt2.bytes_to_unicode
44
+ def bytes_to_unicode():
45
+ """
46
+ Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
47
+ characters the bpe code barfs on.
48
+
49
+ The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
50
+ if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
51
+ decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
52
+ tables between utf-8 bytes and unicode strings.
53
+ """
54
+ bs = (
55
+ list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
56
+ )
57
+ cs = bs[:]
58
+ n = 0
59
+ for b in range(2**8):
60
+ if b not in bs:
61
+ bs.append(b)
62
+ cs.append(2**8 + n)
63
+ n += 1
64
+ cs = [chr(n) for n in cs]
65
+ return dict(zip(bs, cs))
66
+
67
+
68
+ # Copied from transformers.models.gpt2.tokenization_gpt2.get_pairs
69
+ def get_pairs(word):
70
+ """
71
+ Return set of symbol pairs in a word.
72
+
73
+ Word is represented as tuple of symbols (symbols being variable-length strings).
74
+ """
75
+ pairs = set()
76
+ prev_char = word[0]
77
+ for char in word[1:]:
78
+ pairs.add((prev_char, char))
79
+ prev_char = char
80
+ return pairs
81
+
82
+
83
+ class Qwen2Tokenizer(PreTrainedTokenizer):
84
+ """
85
+ Construct a Qwen2 tokenizer. Based on byte-level Byte-Pair-Encoding.
86
+
87
+ Same with GPT2Tokenizer, this tokenizer has been trained to treat spaces like parts of the tokens so a word will
88
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
89
+
90
+ ```python
91
+ >>> from transformers import Qwen2Tokenizer
92
+
93
+ >>> tokenizer = Qwen2Tokenizer.from_pretrained("Qwen/Qwen-tokenizer")
94
+ >>> tokenizer("Hello world")["input_ids"]
95
+ [9707, 1879]
96
+
97
+ >>> tokenizer(" Hello world")["input_ids"]
98
+ [21927, 1879]
99
+ ```
100
+ This is expected.
101
+
102
+ You should not use GPT2Tokenizer instead, because of the different pretokenization rules.
103
+
104
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
105
+ this superclass for more information regarding those methods.
106
+
107
+ Args:
108
+ vocab_file (`str`):
109
+ Path to the vocabulary file.
110
+ merges_file (`str`):
111
+ Path to the merges file.
112
+ errors (`str`, *optional*, defaults to `"replace"`):
113
+ Paradigm to follow when decoding bytes to UTF-8. See
114
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
115
+ unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
116
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
117
+ token instead.
118
+ bos_token (`str`, *optional*):
119
+ The beginning of sequence token. Not applicable for this tokenizer.
120
+ eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
121
+ The end of sequence token.
122
+ pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
123
+ The token used for padding, for example when batching sequences of different lengths.
124
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
125
+ Whether or not the model should cleanup the spaces that were added when splitting the input text during the
126
+ tokenization process. Not applicable to this tokenizer, since tokenization does not add spaces.
127
+ split_special_tokens (`bool`, *optional*, defaults to `False`):
128
+ Whether or not the special tokens should be split during the tokenization process. The default behavior is
129
+ to not split special tokens. This means that if `<|endoftext|>` is the `eos_token`, then `tokenizer.tokenize("<|endoftext|>") =
130
+ ['<|endoftext|>`]. Otherwise, if `split_special_tokens=True`, then `tokenizer.tokenize("<|endoftext|>")` will be give `['<',
131
+ '|', 'endo', 'ft', 'ext', '|', '>']`. This argument is only supported for `slow` tokenizers for the moment.
132
+ """
133
+
134
+ vocab_files_names = VOCAB_FILES_NAMES
135
+ model_input_names = ["input_ids", "attention_mask"]
136
+
137
+ def __init__(
138
+ self,
139
+ vocab_file,
140
+ merges_file,
141
+ errors="replace",
142
+ unk_token="<|endoftext|>",
143
+ bos_token=None,
144
+ eos_token="<|endoftext|>",
145
+ pad_token="<|endoftext|>",
146
+ clean_up_tokenization_spaces=False,
147
+ split_special_tokens=False,
148
+ **kwargs,
149
+ ):
150
+ # Qwen vocab does not contain control tokens; added tokens need to be special
151
+ bos_token = (
152
+ AddedToken(bos_token, lstrip=False, rstrip=False, special=True, normalized=False)
153
+ if isinstance(bos_token, str)
154
+ else bos_token
155
+ )
156
+ eos_token = (
157
+ AddedToken(eos_token, lstrip=False, rstrip=False, special=True, normalized=False)
158
+ if isinstance(eos_token, str)
159
+ else eos_token
160
+ )
161
+ unk_token = (
162
+ AddedToken(unk_token, lstrip=False, rstrip=False, special=True, normalized=False)
163
+ if isinstance(unk_token, str)
164
+ else unk_token
165
+ )
166
+ pad_token = (
167
+ AddedToken(pad_token, lstrip=False, rstrip=False, special=True, normalized=False)
168
+ if isinstance(pad_token, str)
169
+ else pad_token
170
+ )
171
+
172
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
173
+ self.encoder = json.load(vocab_handle)
174
+ self.decoder = {v: k for k, v in self.encoder.items()}
175
+ self.errors = errors # how to handle errors in decoding
176
+ self.byte_encoder = bytes_to_unicode()
177
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
178
+ bpe_merges = []
179
+ with open(merges_file, encoding="utf-8") as merges_handle:
180
+ for i, line in enumerate(merges_handle):
181
+ line = line.strip()
182
+ if (i == 0 and line.startswith("#version:")) or not line:
183
+ continue
184
+ bpe_merges.append(tuple(line.split()))
185
+ self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
186
+ # NOTE: the cache can grow without bound and will get really large for long running processes
187
+ # (esp. for texts of language that do not use space between word, e.g. Chinese); technically
188
+ # not a memory leak but appears as one.
189
+ # GPT2Tokenizer has the same problem, so let's be consistent.
190
+ self.cache = {}
191
+
192
+ self.pat = re.compile(PRETOKENIZE_REGEX)
193
+
194
+ if kwargs.get("add_prefix_space", False):
195
+ logger.warning_once(
196
+ f"{self.__class__.__name} does not support `add_prefix_space`, setting it to True has no effect."
197
+ )
198
+
199
+ super().__init__(
200
+ errors=errors,
201
+ bos_token=bos_token,
202
+ eos_token=eos_token,
203
+ pad_token=pad_token,
204
+ unk_token=unk_token,
205
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
206
+ split_special_tokens=split_special_tokens,
207
+ **kwargs,
208
+ )
209
+
210
+ @property
211
+ def vocab_size(self) -> int:
212
+ return len(self.encoder)
213
+
214
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.get_vocab
215
+ def get_vocab(self):
216
+ return dict(self.encoder, **self.added_tokens_encoder)
217
+
218
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.bpe
219
+ def bpe(self, token):
220
+ if token in self.cache:
221
+ return self.cache[token]
222
+ word = tuple(token)
223
+ pairs = get_pairs(word)
224
+
225
+ if not pairs:
226
+ return token
227
+
228
+ while True:
229
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
230
+ if bigram not in self.bpe_ranks:
231
+ break
232
+ first, second = bigram
233
+ new_word = []
234
+ i = 0
235
+ while i < len(word):
236
+ try:
237
+ j = word.index(first, i)
238
+ except ValueError:
239
+ new_word.extend(word[i:])
240
+ break
241
+ else:
242
+ new_word.extend(word[i:j])
243
+ i = j
244
+
245
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
246
+ new_word.append(first + second)
247
+ i += 2
248
+ else:
249
+ new_word.append(word[i])
250
+ i += 1
251
+ new_word = tuple(new_word)
252
+ word = new_word
253
+ if len(word) == 1:
254
+ break
255
+ else:
256
+ pairs = get_pairs(word)
257
+ word = " ".join(word)
258
+ self.cache[token] = word
259
+ return word
260
+
261
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._tokenize
262
+ def _tokenize(self, text):
263
+ """Tokenize a string."""
264
+ bpe_tokens = []
265
+ for token in re.findall(self.pat, text):
266
+ token = "".join(
267
+ self.byte_encoder[b] for b in token.encode("utf-8")
268
+ ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
269
+ bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
270
+ return bpe_tokens
271
+
272
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._convert_token_to_id
273
+ def _convert_token_to_id(self, token):
274
+ """Converts a token (str) in an id using the vocab."""
275
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
276
+
277
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._convert_id_to_token
278
+ def _convert_id_to_token(self, index):
279
+ """Converts an index (integer) in a token (str) using the vocab."""
280
+ return self.decoder.get(index)
281
+
282
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.convert_tokens_to_string
283
+ def convert_tokens_to_string(self, tokens):
284
+ """Converts a sequence of tokens (string) in a single string."""
285
+ text = "".join(tokens)
286
+ text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
287
+ return text
288
+
289
+ def decode(
290
+ self,
291
+ token_ids,
292
+ skip_special_tokens: bool = False,
293
+ clean_up_tokenization_spaces: Optional[bool] = False,
294
+ spaces_between_special_tokens: bool = False,
295
+ **kwargs,
296
+ ) -> str:
297
+ # `spaces_between_special_tokens` defaults to True for _decode in slow tokenizers
298
+ # and cannot be configured elsewhere, but it should default to False for Qwen2Tokenizer
299
+ return super().decode(
300
+ token_ids,
301
+ skip_special_tokens=skip_special_tokens,
302
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
303
+ spaces_between_special_tokens=spaces_between_special_tokens,
304
+ **kwargs,
305
+ )
306
+
307
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.save_vocabulary
308
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
309
+ if not os.path.isdir(save_directory):
310
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
311
+ return
312
+ vocab_file = os.path.join(
313
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
314
+ )
315
+ merge_file = os.path.join(
316
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
317
+ )
318
+
319
+ with open(vocab_file, "w", encoding="utf-8") as f:
320
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
321
+
322
+ index = 0
323
+ with open(merge_file, "w", encoding="utf-8") as writer:
324
+ writer.write("#version: 0.2\n")
325
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
326
+ if index != token_index:
327
+ logger.warning(
328
+ f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
329
+ " Please check that the tokenizer is not corrupted!"
330
+ )
331
+ index = token_index
332
+ writer.write(" ".join(bpe_tokens) + "\n")
333
+ index += 1
334
+
335
+ return vocab_file, merge_file
336
+
337
+ def prepare_for_tokenization(self, text, **kwargs):
338
+ text = unicodedata.normalize("NFC", text)
339
+ return (text, kwargs)
340
+
341
+
342
+ __all__ = ["Qwen2Tokenizer"]
tokenization_qwen2_fast.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Tokenization classes for Qwen2."""
16
+
17
+ from typing import Optional, Tuple
18
+
19
+ from ...tokenization_utils import AddedToken
20
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
21
+ from ...utils import logging
22
+ from .tokenization_qwen2 import Qwen2Tokenizer
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+ VOCAB_FILES_NAMES = {
28
+ "vocab_file": "vocab.json",
29
+ "merges_file": "merges.txt",
30
+ "tokenizer_file": "tokenizer.json",
31
+ }
32
+
33
+
34
+ MAX_MODEL_INPUT_SIZES = {"qwen/qwen-tokenizer": 32768}
35
+
36
+
37
+ class Qwen2TokenizerFast(PreTrainedTokenizerFast):
38
+ """
39
+ Construct a "fast" Qwen2 tokenizer (backed by HuggingFace's *tokenizers* library). Based on byte-level
40
+ Byte-Pair-Encoding.
41
+
42
+ Same with GPT2Tokenizer, this tokenizer has been trained to treat spaces like parts of the tokens so a word will
43
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
44
+
45
+ ```python
46
+ >>> from transformers import Qwen2TokenizerFast
47
+
48
+ >>> tokenizer = Qwen2TokenizerFast.from_pretrained("Qwen/Qwen-tokenizer")
49
+ >>> tokenizer("Hello world")["input_ids"]
50
+ [9707, 1879]
51
+
52
+ >>> tokenizer(" Hello world")["input_ids"]
53
+ [21927, 1879]
54
+ ```
55
+ This is expected.
56
+
57
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
58
+ refer to this superclass for more information regarding those methods.
59
+
60
+ Args:
61
+ vocab_file (`str`, *optional*):
62
+ Path to the vocabulary file.
63
+ merges_file (`str`, *optional*):
64
+ Path to the merges file.
65
+ tokenizer_file (`str`, *optional*):
66
+ Path to [tokenizers](https://github.com/huggingface/tokenizers) file (generally has a .json extension) that
67
+ contains everything needed to load the tokenizer.
68
+ unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
69
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
70
+ token instead. Not applicable to this tokenizer.
71
+ bos_token (`str`, *optional*):
72
+ The beginning of sequence token. Not applicable for this tokenizer.
73
+ eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
74
+ The end of sequence token.
75
+ pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
76
+ The token used for padding, for example when batching sequences of different lengths.
77
+ """
78
+
79
+ vocab_files_names = VOCAB_FILES_NAMES
80
+ model_input_names = ["input_ids", "attention_mask"]
81
+ slow_tokenizer_class = Qwen2Tokenizer
82
+
83
+ def __init__(
84
+ self,
85
+ vocab_file=None,
86
+ merges_file=None,
87
+ tokenizer_file=None,
88
+ unk_token="<|endoftext|>",
89
+ bos_token=None,
90
+ eos_token="<|endoftext|>",
91
+ pad_token="<|endoftext|>",
92
+ **kwargs,
93
+ ):
94
+ # We need to at least pass vocab_file and merges_file to base class
95
+ # in case a slow tokenizer needs to be initialized; other can be
96
+ # configured through files.
97
+ # following GPT2TokenizerFast, also adding unk_token, bos_token, and eos_token
98
+
99
+ bos_token = (
100
+ AddedToken(bos_token, lstrip=False, rstrip=False, special=True, normalized=False)
101
+ if isinstance(bos_token, str)
102
+ else bos_token
103
+ )
104
+ eos_token = (
105
+ AddedToken(eos_token, lstrip=False, rstrip=False, special=True, normalized=False)
106
+ if isinstance(eos_token, str)
107
+ else eos_token
108
+ )
109
+ unk_token = (
110
+ AddedToken(unk_token, lstrip=False, rstrip=False, special=True, normalized=False)
111
+ if isinstance(unk_token, str)
112
+ else unk_token
113
+ )
114
+ pad_token = (
115
+ AddedToken(pad_token, lstrip=False, rstrip=False, special=True, normalized=False)
116
+ if isinstance(pad_token, str)
117
+ else pad_token
118
+ )
119
+
120
+ super().__init__(
121
+ vocab_file=vocab_file,
122
+ merges_file=merges_file,
123
+ tokenizer_file=tokenizer_file,
124
+ unk_token=unk_token,
125
+ bos_token=bos_token,
126
+ eos_token=eos_token,
127
+ pad_token=pad_token,
128
+ **kwargs,
129
+ )
130
+
131
+ # Copied from transformers.models.gpt2.tokenization_gpt2_fast.GPT2TokenizerFast.save_vocabulary
132
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
133
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
134
+ return tuple(files)
135
+
136
+
137
+ __all__ = ["Qwen2TokenizerFast"]
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:37578395e36d9b7cf7fc87a3cc562f03fc7c2b9d480b3780c18ccbb838968bbc
3
+ size 11423007
tokenizer_config.json ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "151643": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "151644": {
14
+ "content": "<|im_start|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "151645": {
22
+ "content": "<|im_end|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "151646": {
30
+ "content": "<|object_ref_start|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "151647": {
38
+ "content": "<|object_ref_end|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "151648": {
46
+ "content": "<|box_start|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "151649": {
54
+ "content": "<|box_end|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "151650": {
62
+ "content": "<|quad_start|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "151651": {
70
+ "content": "<|quad_end|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "151652": {
78
+ "content": "<|vision_start|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "151653": {
86
+ "content": "<|vision_end|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "151654": {
94
+ "content": "<|vision_pad|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "151655": {
102
+ "content": "<|image_pad|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "151656": {
110
+ "content": "<|video_pad|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "151657": {
118
+ "content": "<tool_call>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": false
124
+ },
125
+ "151658": {
126
+ "content": "</tool_call>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": false
132
+ },
133
+ "151659": {
134
+ "content": "<|fim_prefix|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": false
140
+ },
141
+ "151660": {
142
+ "content": "<|fim_middle|>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": false
148
+ },
149
+ "151661": {
150
+ "content": "<|fim_suffix|>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": false
156
+ },
157
+ "151662": {
158
+ "content": "<|fim_pad|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": false
164
+ },
165
+ "151663": {
166
+ "content": "<|repo_name|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": false
172
+ },
173
+ "151664": {
174
+ "content": "<|file_sep|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": false
180
+ },
181
+ "151665": {
182
+ "content": "<tool_response>",
183
+ "lstrip": false,
184
+ "normalized": false,
185
+ "rstrip": false,
186
+ "single_word": false,
187
+ "special": false
188
+ },
189
+ "151666": {
190
+ "content": "</tool_response>",
191
+ "lstrip": false,
192
+ "normalized": false,
193
+ "rstrip": false,
194
+ "single_word": false,
195
+ "special": false
196
+ },
197
+ "151667": {
198
+ "content": "<think>",
199
+ "lstrip": false,
200
+ "normalized": false,
201
+ "rstrip": false,
202
+ "single_word": false,
203
+ "special": false
204
+ },
205
+ "151668": {
206
+ "content": "</think>",
207
+ "lstrip": false,
208
+ "normalized": false,
209
+ "rstrip": false,
210
+ "single_word": false,
211
+ "special": false
212
+ },
213
+ "151669": {
214
+ "content": "<|MASK|>",
215
+ "lstrip": false,
216
+ "normalized": false,
217
+ "rstrip": false,
218
+ "single_word": false,
219
+ "special": true
220
+ }
221
+ },
222
+ "additional_special_tokens": [
223
+ "<|im_start|>",
224
+ "<|im_end|>",
225
+ "<|object_ref_start|>",
226
+ "<|object_ref_end|>",
227
+ "<|box_start|>",
228
+ "<|box_end|>",
229
+ "<|quad_start|>",
230
+ "<|quad_end|>",
231
+ "<|vision_start|>",
232
+ "<|vision_end|>",
233
+ "<|vision_pad|>",
234
+ "<|image_pad|>",
235
+ "<|video_pad|>"
236
+ ],
237
+ "bos_token": null,
238
+ "clean_up_tokenization_spaces": false,
239
+ "eos_token": "<|im_end|>",
240
+ "errors": "replace",
241
+ "extra_special_tokens": {},
242
+ "mask_token": "<|MASK|>",
243
+ "model_max_length": 131072,
244
+ "pad_token": "<|endoftext|>",
245
+ "split_special_tokens": false,
246
+ "tokenizer_class": "Qwen2Tokenizer",
247
+ "unk_token": null
248
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff