[model] add prm: Skywork-o1-Open-PRM-Qwen2.5-1.5B
Browse files- added_tokens.json +24 -0
- config.json +33 -0
- configuration_qwen2_rm.py +133 -0
- merges.txt +0 -0
- modeling_qwen2_rm.py +1557 -0
- pytorch_model.bin +3 -0
- special_tokens_map.json +32 -0
- tokenizer.json +0 -0
- tokenizer_config.json +207 -0
- vocab.json +0 -0
added_tokens.json
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"</tool_call>": 151658,
|
3 |
+
"<tool_call>": 151657,
|
4 |
+
"<|box_end|>": 151649,
|
5 |
+
"<|box_start|>": 151648,
|
6 |
+
"<|endoftext|>": 151643,
|
7 |
+
"<|file_sep|>": 151664,
|
8 |
+
"<|fim_middle|>": 151660,
|
9 |
+
"<|fim_pad|>": 151662,
|
10 |
+
"<|fim_prefix|>": 151659,
|
11 |
+
"<|fim_suffix|>": 151661,
|
12 |
+
"<|im_end|>": 151645,
|
13 |
+
"<|im_start|>": 151644,
|
14 |
+
"<|image_pad|>": 151655,
|
15 |
+
"<|object_ref_end|>": 151647,
|
16 |
+
"<|object_ref_start|>": 151646,
|
17 |
+
"<|quad_end|>": 151651,
|
18 |
+
"<|quad_start|>": 151650,
|
19 |
+
"<|repo_name|>": 151663,
|
20 |
+
"<|video_pad|>": 151656,
|
21 |
+
"<|vision_end|>": 151653,
|
22 |
+
"<|vision_pad|>": 151654,
|
23 |
+
"<|vision_start|>": 151652
|
24 |
+
}
|
config.json
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"Qwen2ForPrmModel"
|
4 |
+
],
|
5 |
+
"auto_map": {
|
6 |
+
"AutoConfig": "configuration_qwen2_rm.Qwen2RMConfig",
|
7 |
+
"AutoModel": "modeling_qwen2_rm.Qwen2ForRewardModel"
|
8 |
+
},
|
9 |
+
"attention_dropout": 0.0,
|
10 |
+
"bos_token_id": 151643,
|
11 |
+
"end_token_id": 151645,
|
12 |
+
"eos_token_id": 151645,
|
13 |
+
"hidden_act": "silu",
|
14 |
+
"hidden_size": 1536,
|
15 |
+
"initializer_range": 0.02,
|
16 |
+
"intermediate_size": 8960,
|
17 |
+
"max_position_embeddings": 4096,
|
18 |
+
"max_window_layers": 21,
|
19 |
+
"model_type": "qwen2",
|
20 |
+
"num_attention_heads": 12,
|
21 |
+
"num_hidden_layers": 28,
|
22 |
+
"num_key_value_heads": 2,
|
23 |
+
"pad_token_id": 151643,
|
24 |
+
"rms_norm_eps": 1e-06,
|
25 |
+
"rope_theta": 10000.0,
|
26 |
+
"sliding_window": null,
|
27 |
+
"tie_word_embeddings": true,
|
28 |
+
"torch_dtype": "bfloat16",
|
29 |
+
"transformers_version": "4.44.0.dev0",
|
30 |
+
"use_cache": true,
|
31 |
+
"use_sliding_window": false,
|
32 |
+
"vocab_size": 151936
|
33 |
+
}
|
configuration_qwen2_rm.py
ADDED
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
|
24 |
+
class Qwen2RMConfig(PretrainedConfig):
|
25 |
+
r"""
|
26 |
+
This is the configuration class to store the configuration of a [`Qwen2Model`]. It is used to instantiate a
|
27 |
+
Qwen2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
28 |
+
with the defaults will yield a similar configuration to that of
|
29 |
+
Qwen2-7B-beta [Qwen/Qwen2-7B-beta](https://huggingface.co/Qwen/Qwen2-7B-beta).
|
30 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
31 |
+
documentation from [`PretrainedConfig`] for more information.
|
32 |
+
Args:
|
33 |
+
vocab_size (`int`, *optional*, defaults to 151936):
|
34 |
+
Vocabulary size of the Qwen2 model. Defines the number of different tokens that can be represented by the
|
35 |
+
`inputs_ids` passed when calling [`Qwen2Model`]
|
36 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
37 |
+
Dimension of the hidden representations.
|
38 |
+
intermediate_size (`int`, *optional*, defaults to 22016):
|
39 |
+
Dimension of the MLP representations.
|
40 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
41 |
+
Number of hidden layers in the Transformer encoder.
|
42 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
43 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
44 |
+
num_key_value_heads (`int`, *optional*, defaults to 32):
|
45 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
46 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
47 |
+
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
48 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
49 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
50 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
|
51 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
52 |
+
The non-linear activation function (function or string) in the decoder.
|
53 |
+
max_position_embeddings (`int`, *optional*, defaults to 32768):
|
54 |
+
The maximum sequence length that this model might ever be used with.
|
55 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
56 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
57 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
58 |
+
The epsilon used by the rms normalization layers.
|
59 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
60 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
61 |
+
relevant if `config.is_decoder=True`.
|
62 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
63 |
+
Whether the model's input and output word embeddings should be tied.
|
64 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
65 |
+
The base period of the RoPE embeddings.
|
66 |
+
use_sliding_window (`bool`, *optional*, defaults to `False`):
|
67 |
+
Whether to use sliding window attention.
|
68 |
+
sliding_window (`int`, *optional*, defaults to 4096):
|
69 |
+
Sliding window attention (SWA) window size. If not specified, will default to `4096`.
|
70 |
+
max_window_layers (`int`, *optional*, defaults to 28):
|
71 |
+
The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
|
72 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
73 |
+
The dropout ratio for the attention probabilities.
|
74 |
+
```python
|
75 |
+
>>> from transformers import Qwen2Model, Qwen2Config
|
76 |
+
>>> # Initializing a Qwen2 style configuration
|
77 |
+
>>> configuration = Qwen2Config()
|
78 |
+
>>> # Initializing a model from the Qwen2-7B style configuration
|
79 |
+
>>> model = Qwen2Model(configuration)
|
80 |
+
>>> # Accessing the model configuration
|
81 |
+
>>> configuration = model.config
|
82 |
+
```"""
|
83 |
+
|
84 |
+
model_type = "qwen2"
|
85 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
86 |
+
|
87 |
+
def __init__(
|
88 |
+
self,
|
89 |
+
vocab_size=151936,
|
90 |
+
hidden_size=4096,
|
91 |
+
intermediate_size=22016,
|
92 |
+
num_hidden_layers=32,
|
93 |
+
num_attention_heads=32,
|
94 |
+
num_key_value_heads=32,
|
95 |
+
hidden_act="silu",
|
96 |
+
max_position_embeddings=32768,
|
97 |
+
initializer_range=0.02,
|
98 |
+
rms_norm_eps=1e-6,
|
99 |
+
use_cache=True,
|
100 |
+
tie_word_embeddings=False,
|
101 |
+
rope_theta=10000.0,
|
102 |
+
use_sliding_window=False,
|
103 |
+
sliding_window=4096,
|
104 |
+
max_window_layers=28,
|
105 |
+
attention_dropout=0.0,
|
106 |
+
**kwargs,
|
107 |
+
):
|
108 |
+
self.vocab_size = vocab_size
|
109 |
+
self.max_position_embeddings = max_position_embeddings
|
110 |
+
self.hidden_size = hidden_size
|
111 |
+
self.intermediate_size = intermediate_size
|
112 |
+
self.num_hidden_layers = num_hidden_layers
|
113 |
+
self.num_attention_heads = num_attention_heads
|
114 |
+
self.use_sliding_window = use_sliding_window
|
115 |
+
self.sliding_window = sliding_window if use_sliding_window else None
|
116 |
+
self.max_window_layers = max_window_layers
|
117 |
+
|
118 |
+
# for backward compatibility
|
119 |
+
if num_key_value_heads is None:
|
120 |
+
num_key_value_heads = num_attention_heads
|
121 |
+
|
122 |
+
self.num_key_value_heads = num_key_value_heads
|
123 |
+
self.hidden_act = hidden_act
|
124 |
+
self.initializer_range = initializer_range
|
125 |
+
self.rms_norm_eps = rms_norm_eps
|
126 |
+
self.use_cache = use_cache
|
127 |
+
self.rope_theta = rope_theta
|
128 |
+
self.attention_dropout = attention_dropout
|
129 |
+
|
130 |
+
super().__init__(
|
131 |
+
tie_word_embeddings=tie_word_embeddings,
|
132 |
+
**kwargs,
|
133 |
+
)
|
merges.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
modeling_qwen2_rm.py
ADDED
@@ -0,0 +1,1557 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
|
22 |
+
import math
|
23 |
+
from typing import List, Optional, Tuple, Union
|
24 |
+
|
25 |
+
import torch
|
26 |
+
import torch.utils.checkpoint
|
27 |
+
from torch import nn
|
28 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
29 |
+
|
30 |
+
from transformers.activations import ACT2FN
|
31 |
+
from transformers.cache_utils import Cache, DynamicCache#, StaticCache
|
32 |
+
from transformers.modeling_attn_mask_utils import AttentionMaskConverter
|
33 |
+
from transformers.modeling_outputs import (
|
34 |
+
BaseModelOutputWithPast,
|
35 |
+
CausalLMOutputWithPast,
|
36 |
+
SequenceClassifierOutputWithPast,
|
37 |
+
TokenClassifierOutput,
|
38 |
+
)
|
39 |
+
from transformers.modeling_utils import PreTrainedModel
|
40 |
+
from transformers.utils import (
|
41 |
+
add_start_docstrings,
|
42 |
+
add_start_docstrings_to_model_forward,
|
43 |
+
is_flash_attn_2_available,
|
44 |
+
is_flash_attn_greater_or_equal_2_10,
|
45 |
+
logging,
|
46 |
+
replace_return_docstrings,
|
47 |
+
)
|
48 |
+
from .configuration_qwen2_rm import Qwen2RMConfig as Qwen2Config
|
49 |
+
|
50 |
+
|
51 |
+
if is_flash_attn_2_available():
|
52 |
+
from transformers.modeling_flash_attention_utils import _flash_attention_forward
|
53 |
+
|
54 |
+
|
55 |
+
logger = logging.get_logger(__name__)
|
56 |
+
|
57 |
+
|
58 |
+
_CHECKPOINT_FOR_DOC = "Qwen/Qwen2-7B-beta"
|
59 |
+
_CONFIG_FOR_DOC = "Qwen2Config"
|
60 |
+
|
61 |
+
|
62 |
+
# Copied from transformers.models.llama.modeling_llama._prepare_4d_causal_attention_mask_with_cache_position
|
63 |
+
def _prepare_4d_causal_attention_mask_with_cache_position(
|
64 |
+
attention_mask: torch.Tensor,
|
65 |
+
sequence_length: int,
|
66 |
+
target_length: int,
|
67 |
+
dtype: torch.dtype,
|
68 |
+
device: torch.device,
|
69 |
+
min_dtype: float,
|
70 |
+
cache_position: torch.Tensor,
|
71 |
+
batch_size: int,
|
72 |
+
):
|
73 |
+
"""
|
74 |
+
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
|
75 |
+
`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
|
76 |
+
Args:
|
77 |
+
attention_mask (`torch.Tensor`):
|
78 |
+
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)`.
|
79 |
+
sequence_length (`int`):
|
80 |
+
The sequence length being processed.
|
81 |
+
target_length (`int`):
|
82 |
+
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.
|
83 |
+
dtype (`torch.dtype`):
|
84 |
+
The dtype to use for the 4D attention mask.
|
85 |
+
device (`torch.device`):
|
86 |
+
The device to plcae the 4D attention mask on.
|
87 |
+
min_dtype (`float`):
|
88 |
+
The minimum value representable with the dtype `dtype`.
|
89 |
+
cache_position (`torch.Tensor`):
|
90 |
+
Indices depicting the position of the input sequence tokens in the sequence.
|
91 |
+
batch_size (`torch.Tensor`):
|
92 |
+
Batch size.
|
93 |
+
"""
|
94 |
+
if attention_mask is not None and attention_mask.dim() == 4:
|
95 |
+
# In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
|
96 |
+
causal_mask = attention_mask
|
97 |
+
else:
|
98 |
+
causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
|
99 |
+
if sequence_length != 1:
|
100 |
+
causal_mask = torch.triu(causal_mask, diagonal=1)
|
101 |
+
causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
|
102 |
+
causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
|
103 |
+
if attention_mask is not None:
|
104 |
+
causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
|
105 |
+
mask_length = attention_mask.shape[-1]
|
106 |
+
padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
|
107 |
+
padding_mask = padding_mask == 0
|
108 |
+
causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
|
109 |
+
padding_mask, min_dtype
|
110 |
+
)
|
111 |
+
|
112 |
+
return causal_mask
|
113 |
+
|
114 |
+
|
115 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Qwen2
|
116 |
+
class Qwen2RMSNorm(nn.Module):
|
117 |
+
def __init__(self, hidden_size, eps=1e-6):
|
118 |
+
"""
|
119 |
+
Qwen2RMSNorm is equivalent to T5LayerNorm
|
120 |
+
"""
|
121 |
+
super().__init__()
|
122 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
123 |
+
self.variance_epsilon = eps
|
124 |
+
|
125 |
+
def forward(self, hidden_states):
|
126 |
+
input_dtype = hidden_states.dtype
|
127 |
+
hidden_states = hidden_states.to(torch.float32)
|
128 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
129 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
130 |
+
return self.weight * hidden_states.to(input_dtype)
|
131 |
+
|
132 |
+
def extra_repr(self):
|
133 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
134 |
+
|
135 |
+
|
136 |
+
# Copied from transformers.models.mixtral.modeling_mixtral.MixtralRotaryEmbedding with Mixtral->Qwen2
|
137 |
+
class Qwen2RotaryEmbedding(nn.Module):
|
138 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
139 |
+
super().__init__()
|
140 |
+
|
141 |
+
self.dim = dim
|
142 |
+
self.max_position_embeddings = max_position_embeddings
|
143 |
+
self.base = base
|
144 |
+
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
|
145 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
146 |
+
|
147 |
+
# Build here to make `torch.jit.trace` work.
|
148 |
+
self._set_cos_sin_cache(
|
149 |
+
seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
|
150 |
+
)
|
151 |
+
|
152 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
153 |
+
self.max_seq_len_cached = seq_len
|
154 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
|
155 |
+
|
156 |
+
freqs = torch.outer(t, self.inv_freq)
|
157 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
158 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
159 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
160 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
161 |
+
|
162 |
+
def forward(self, x, seq_len=None):
|
163 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
164 |
+
if seq_len > self.max_seq_len_cached:
|
165 |
+
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
166 |
+
|
167 |
+
return (
|
168 |
+
self.cos_cached[:seq_len].to(dtype=x.dtype),
|
169 |
+
self.sin_cached[:seq_len].to(dtype=x.dtype),
|
170 |
+
)
|
171 |
+
|
172 |
+
|
173 |
+
# Copied from transformers.models.llama.modeling_llama.rotate_half
|
174 |
+
def rotate_half(x):
|
175 |
+
"""Rotates half the hidden dims of the input."""
|
176 |
+
x1 = x[..., : x.shape[-1] // 2]
|
177 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
178 |
+
return torch.cat((-x2, x1), dim=-1)
|
179 |
+
|
180 |
+
|
181 |
+
# Copied from transformers.models.mixtral.modeling_mixtral.apply_rotary_pos_emb
|
182 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
|
183 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
184 |
+
Args:
|
185 |
+
q (`torch.Tensor`): The query tensor.
|
186 |
+
k (`torch.Tensor`): The key tensor.
|
187 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
188 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
189 |
+
position_ids (`torch.Tensor`):
|
190 |
+
The position indices of the tokens corresponding to the query and key tensors. For example, this can be
|
191 |
+
used to pass offsetted position ids when working with a KV-cache.
|
192 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
193 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
194 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
195 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
196 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
197 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
198 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
199 |
+
Returns:
|
200 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
201 |
+
"""
|
202 |
+
cos = cos[position_ids].unsqueeze(unsqueeze_dim)
|
203 |
+
sin = sin[position_ids].unsqueeze(unsqueeze_dim)
|
204 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
205 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
206 |
+
return q_embed, k_embed
|
207 |
+
|
208 |
+
|
209 |
+
# Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Qwen2
|
210 |
+
class Qwen2MLP(nn.Module):
|
211 |
+
def __init__(self, config):
|
212 |
+
super().__init__()
|
213 |
+
self.hidden_size = config.hidden_size
|
214 |
+
self.intermediate_size = config.intermediate_size
|
215 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
216 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
217 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
218 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
219 |
+
|
220 |
+
def forward(self, hidden_state):
|
221 |
+
return self.down_proj(self.act_fn(self.gate_proj(hidden_state)) * self.up_proj(hidden_state))
|
222 |
+
|
223 |
+
|
224 |
+
# Copied from transformers.models.llama.modeling_llama.repeat_kv
|
225 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
226 |
+
"""
|
227 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
228 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
229 |
+
"""
|
230 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
231 |
+
if n_rep == 1:
|
232 |
+
return hidden_states
|
233 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
234 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
235 |
+
|
236 |
+
|
237 |
+
class Qwen2Attention(nn.Module):
|
238 |
+
"""
|
239 |
+
Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
|
240 |
+
and "Generating Long Sequences with Sparse Transformers".
|
241 |
+
"""
|
242 |
+
|
243 |
+
def __init__(self, config: Qwen2Config, layer_idx: Optional[int] = None):
|
244 |
+
super().__init__()
|
245 |
+
self.config = config
|
246 |
+
self.layer_idx = layer_idx
|
247 |
+
if layer_idx is None:
|
248 |
+
logger.warning_once(
|
249 |
+
f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
|
250 |
+
"to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
|
251 |
+
"when creating this class."
|
252 |
+
)
|
253 |
+
|
254 |
+
self.hidden_size = config.hidden_size
|
255 |
+
self.num_heads = config.num_attention_heads
|
256 |
+
self.head_dim = self.hidden_size // self.num_heads
|
257 |
+
self.num_key_value_heads = config.num_key_value_heads
|
258 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
259 |
+
self.max_position_embeddings = config.max_position_embeddings
|
260 |
+
self.rope_theta = config.rope_theta
|
261 |
+
self.is_causal = True
|
262 |
+
self.attention_dropout = config.attention_dropout
|
263 |
+
|
264 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
265 |
+
raise ValueError(
|
266 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
267 |
+
f" and `num_heads`: {self.num_heads})."
|
268 |
+
)
|
269 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
|
270 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
|
271 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
|
272 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
273 |
+
|
274 |
+
self.rotary_emb = Qwen2RotaryEmbedding(
|
275 |
+
self.head_dim,
|
276 |
+
max_position_embeddings=self.max_position_embeddings,
|
277 |
+
base=self.rope_theta,
|
278 |
+
)
|
279 |
+
|
280 |
+
def forward(
|
281 |
+
self,
|
282 |
+
hidden_states: torch.Tensor,
|
283 |
+
attention_mask: Optional[torch.Tensor] = None,
|
284 |
+
position_ids: Optional[torch.LongTensor] = None,
|
285 |
+
past_key_value: Optional[Cache] = None,
|
286 |
+
output_attentions: bool = False,
|
287 |
+
use_cache: bool = False,
|
288 |
+
cache_position: Optional[torch.LongTensor] = None,
|
289 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
290 |
+
bsz, q_len, _ = hidden_states.size()
|
291 |
+
|
292 |
+
query_states = self.q_proj(hidden_states)
|
293 |
+
key_states = self.k_proj(hidden_states)
|
294 |
+
value_states = self.v_proj(hidden_states)
|
295 |
+
|
296 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
297 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
298 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
299 |
+
|
300 |
+
kv_seq_len = key_states.shape[-2]
|
301 |
+
if past_key_value is not None:
|
302 |
+
if self.layer_idx is None:
|
303 |
+
raise ValueError(
|
304 |
+
f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
|
305 |
+
"for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
|
306 |
+
"with a layer index."
|
307 |
+
)
|
308 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
309 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
310 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
311 |
+
|
312 |
+
if past_key_value is not None:
|
313 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
|
314 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
315 |
+
|
316 |
+
# repeat k/v heads if n_kv_heads < n_heads
|
317 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
318 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
319 |
+
|
320 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
321 |
+
|
322 |
+
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
323 |
+
raise ValueError(
|
324 |
+
f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
|
325 |
+
f" {attn_weights.size()}"
|
326 |
+
)
|
327 |
+
|
328 |
+
if attention_mask is not None: # no matter the length, we just slice it
|
329 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
330 |
+
attn_weights = attn_weights + causal_mask
|
331 |
+
|
332 |
+
# upcast attention to fp32
|
333 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
334 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
335 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
336 |
+
|
337 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
338 |
+
raise ValueError(
|
339 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
340 |
+
f" {attn_output.size()}"
|
341 |
+
)
|
342 |
+
|
343 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
344 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
345 |
+
|
346 |
+
attn_output = self.o_proj(attn_output)
|
347 |
+
|
348 |
+
if not output_attentions:
|
349 |
+
attn_weights = None
|
350 |
+
|
351 |
+
return attn_output, attn_weights, past_key_value
|
352 |
+
|
353 |
+
|
354 |
+
class Qwen2FlashAttention2(Qwen2Attention):
|
355 |
+
"""
|
356 |
+
Qwen2 flash attention module, following Qwen2 attention module. This module inherits from `Qwen2Attention`
|
357 |
+
as the weights of the module stays untouched. The only required change would be on the forward pass
|
358 |
+
where it needs to correctly call the public API of flash attention and deal with padding tokens
|
359 |
+
in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
|
360 |
+
config.max_window_layers layers.
|
361 |
+
"""
|
362 |
+
|
363 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
|
364 |
+
def __init__(self, *args, **kwargs):
|
365 |
+
super().__init__(*args, **kwargs)
|
366 |
+
|
367 |
+
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
368 |
+
# 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.
|
369 |
+
# 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).
|
370 |
+
self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
371 |
+
|
372 |
+
def forward(
|
373 |
+
self,
|
374 |
+
hidden_states: torch.Tensor,
|
375 |
+
attention_mask: Optional[torch.Tensor] = None,
|
376 |
+
position_ids: Optional[torch.LongTensor] = None,
|
377 |
+
past_key_value: Optional[Cache] = None,
|
378 |
+
output_attentions: bool = False,
|
379 |
+
use_cache: bool = False,
|
380 |
+
cache_position: Optional[torch.LongTensor] = None,
|
381 |
+
):
|
382 |
+
bsz, q_len, _ = hidden_states.size()
|
383 |
+
|
384 |
+
query_states = self.q_proj(hidden_states)
|
385 |
+
key_states = self.k_proj(hidden_states)
|
386 |
+
value_states = self.v_proj(hidden_states)
|
387 |
+
|
388 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
389 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
390 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
391 |
+
|
392 |
+
kv_seq_len = key_states.shape[-2]
|
393 |
+
if past_key_value is not None:
|
394 |
+
if self.layer_idx is None:
|
395 |
+
raise ValueError(
|
396 |
+
f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
|
397 |
+
"for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
|
398 |
+
"with a layer index."
|
399 |
+
)
|
400 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
401 |
+
|
402 |
+
# Because the input can be padded, the absolute sequence length depends on the max position id.
|
403 |
+
rotary_seq_len = (
|
404 |
+
max(kv_seq_len, position_ids[:, -1].max().item() + 1) if position_ids is not None else kv_seq_len
|
405 |
+
)
|
406 |
+
|
407 |
+
cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
|
408 |
+
|
409 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
410 |
+
|
411 |
+
if past_key_value is not None:
|
412 |
+
# Activate slicing cache only if the config has a value `sliding_windows` attribute
|
413 |
+
cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
|
414 |
+
if (
|
415 |
+
getattr(self.config, "sliding_window", None) is not None
|
416 |
+
and kv_seq_len > self.config.sliding_window
|
417 |
+
and cache_has_contents
|
418 |
+
):
|
419 |
+
slicing_tokens = 1 - self.config.sliding_window
|
420 |
+
|
421 |
+
past_key = past_key_value[self.layer_idx][0]
|
422 |
+
past_value = past_key_value[self.layer_idx][1]
|
423 |
+
|
424 |
+
past_key = past_key[:, :, slicing_tokens:, :].contiguous()
|
425 |
+
past_value = past_value[:, :, slicing_tokens:, :].contiguous()
|
426 |
+
|
427 |
+
if past_key.shape[-2] != self.config.sliding_window - 1:
|
428 |
+
raise ValueError(
|
429 |
+
f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
|
430 |
+
f" {past_key.shape}"
|
431 |
+
)
|
432 |
+
|
433 |
+
if attention_mask is not None:
|
434 |
+
attention_mask = attention_mask[:, slicing_tokens:]
|
435 |
+
attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
|
436 |
+
|
437 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
|
438 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
439 |
+
|
440 |
+
# repeat k/v heads if n_kv_heads < n_heads
|
441 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
442 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
443 |
+
dropout_rate = 0.0 if not self.training else self.attention_dropout
|
444 |
+
|
445 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
446 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
447 |
+
# cast them back in float16 just to be sure everything works as expected.
|
448 |
+
input_dtype = query_states.dtype
|
449 |
+
if input_dtype == torch.float32:
|
450 |
+
if torch.is_autocast_enabled():
|
451 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
452 |
+
# Handle the case where the model is quantized
|
453 |
+
elif hasattr(self.config, "_pre_quantization_dtype"):
|
454 |
+
target_dtype = self.config._pre_quantization_dtype
|
455 |
+
else:
|
456 |
+
target_dtype = self.q_proj.weight.dtype
|
457 |
+
|
458 |
+
logger.warning_once(
|
459 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
460 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
461 |
+
f" {target_dtype}."
|
462 |
+
)
|
463 |
+
|
464 |
+
query_states = query_states.to(target_dtype)
|
465 |
+
key_states = key_states.to(target_dtype)
|
466 |
+
value_states = value_states.to(target_dtype)
|
467 |
+
|
468 |
+
# Reashape to the expected shape for Flash Attention
|
469 |
+
query_states = query_states.transpose(1, 2)
|
470 |
+
key_states = key_states.transpose(1, 2)
|
471 |
+
value_states = value_states.transpose(1, 2)
|
472 |
+
|
473 |
+
if (
|
474 |
+
self.config.use_sliding_window
|
475 |
+
and getattr(self.config, "sliding_window", None) is not None
|
476 |
+
and self.layer_idx >= self.config.max_window_layers
|
477 |
+
):
|
478 |
+
sliding_window = self.config.sliding_window
|
479 |
+
else:
|
480 |
+
sliding_window = None
|
481 |
+
|
482 |
+
attn_output = _flash_attention_forward(
|
483 |
+
query_states,
|
484 |
+
key_states,
|
485 |
+
value_states,
|
486 |
+
attention_mask,
|
487 |
+
q_len,
|
488 |
+
position_ids=position_ids,
|
489 |
+
dropout=dropout_rate,
|
490 |
+
sliding_window=sliding_window,
|
491 |
+
is_causal=self.is_causal,
|
492 |
+
use_top_left_mask=self._flash_attn_uses_top_left_mask,
|
493 |
+
)
|
494 |
+
|
495 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
|
496 |
+
attn_output = self.o_proj(attn_output)
|
497 |
+
|
498 |
+
if not output_attentions:
|
499 |
+
attn_weights = None
|
500 |
+
|
501 |
+
return attn_output, attn_weights, past_key_value
|
502 |
+
|
503 |
+
|
504 |
+
# Copied from transformers.models.mixtral.modeling_mixtral.MixtralSdpaAttention with Mixtral->Qwen2
|
505 |
+
class Qwen2SdpaAttention(Qwen2Attention):
|
506 |
+
"""
|
507 |
+
Qwen2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
|
508 |
+
`Qwen2Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
|
509 |
+
SDPA API.
|
510 |
+
"""
|
511 |
+
|
512 |
+
# Adapted from Qwen2Attention.forward
|
513 |
+
def forward(
|
514 |
+
self,
|
515 |
+
hidden_states: torch.Tensor,
|
516 |
+
attention_mask: Optional[torch.Tensor] = 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 |
+
cache_position: Optional[torch.LongTensor] = None,
|
522 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
523 |
+
if output_attentions:
|
524 |
+
# TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
|
525 |
+
logger.warning_once(
|
526 |
+
"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, "
|
527 |
+
'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.'
|
528 |
+
)
|
529 |
+
return super().forward(
|
530 |
+
hidden_states=hidden_states,
|
531 |
+
attention_mask=attention_mask,
|
532 |
+
position_ids=position_ids,
|
533 |
+
past_key_value=past_key_value,
|
534 |
+
output_attentions=output_attentions,
|
535 |
+
use_cache=use_cache,
|
536 |
+
)
|
537 |
+
|
538 |
+
bsz, q_len, _ = hidden_states.size()
|
539 |
+
|
540 |
+
query_states = self.q_proj(hidden_states)
|
541 |
+
key_states = self.k_proj(hidden_states)
|
542 |
+
value_states = self.v_proj(hidden_states)
|
543 |
+
|
544 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
545 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
546 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
547 |
+
|
548 |
+
kv_seq_len = key_states.shape[-2]
|
549 |
+
if past_key_value is not None:
|
550 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
551 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
552 |
+
|
553 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
554 |
+
|
555 |
+
if past_key_value is not None:
|
556 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
|
557 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
558 |
+
|
559 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
560 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
561 |
+
|
562 |
+
causal_mask = attention_mask
|
563 |
+
if attention_mask is not None: # no matter the length, we just slice it
|
564 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
565 |
+
|
566 |
+
# SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
|
567 |
+
# Reference: https://github.com/pytorch/pytorch/issues/112577.
|
568 |
+
if query_states.device.type == "cuda" and attention_mask is not None:
|
569 |
+
query_states = query_states.contiguous()
|
570 |
+
key_states = key_states.contiguous()
|
571 |
+
value_states = value_states.contiguous()
|
572 |
+
|
573 |
+
# We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
|
574 |
+
# in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
|
575 |
+
# 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.
|
576 |
+
is_causal = True if causal_mask is None and q_len > 1 else False
|
577 |
+
|
578 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
579 |
+
query_states,
|
580 |
+
key_states,
|
581 |
+
value_states,
|
582 |
+
attn_mask=causal_mask,
|
583 |
+
dropout_p=self.attention_dropout if self.training else 0.0,
|
584 |
+
is_causal=is_causal,
|
585 |
+
)
|
586 |
+
|
587 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
588 |
+
attn_output = attn_output.view(bsz, q_len, self.hidden_size)
|
589 |
+
|
590 |
+
attn_output = self.o_proj(attn_output)
|
591 |
+
|
592 |
+
return attn_output, None, past_key_value
|
593 |
+
|
594 |
+
|
595 |
+
QWEN2_ATTENTION_CLASSES = {
|
596 |
+
"eager": Qwen2Attention,
|
597 |
+
"flash_attention_2": Qwen2FlashAttention2,
|
598 |
+
"sdpa": Qwen2SdpaAttention,
|
599 |
+
}
|
600 |
+
|
601 |
+
|
602 |
+
class Qwen2DecoderLayer(nn.Module):
|
603 |
+
def __init__(self, config: Qwen2Config, layer_idx: int):
|
604 |
+
super().__init__()
|
605 |
+
self.hidden_size = config.hidden_size
|
606 |
+
|
607 |
+
if config.sliding_window and config._attn_implementation != "flash_attention_2":
|
608 |
+
logger.warning_once(
|
609 |
+
f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
|
610 |
+
"unexpected results may be encountered."
|
611 |
+
)
|
612 |
+
self.self_attn = QWEN2_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
|
613 |
+
|
614 |
+
self.mlp = Qwen2MLP(config)
|
615 |
+
self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
616 |
+
self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
617 |
+
|
618 |
+
def forward(
|
619 |
+
self,
|
620 |
+
hidden_states: torch.Tensor,
|
621 |
+
attention_mask: Optional[torch.Tensor] = None,
|
622 |
+
position_ids: Optional[torch.LongTensor] = None,
|
623 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
624 |
+
output_attentions: Optional[bool] = False,
|
625 |
+
use_cache: Optional[bool] = False,
|
626 |
+
cache_position: Optional[torch.LongTensor] = None,
|
627 |
+
**kwargs,
|
628 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
629 |
+
"""
|
630 |
+
Args:
|
631 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
632 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
633 |
+
`(batch, sequence_length)` where padding elements are indicated by 0.
|
634 |
+
output_attentions (`bool`, *optional*):
|
635 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
636 |
+
returned tensors for more detail.
|
637 |
+
use_cache (`bool`, *optional*):
|
638 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
639 |
+
(see `past_key_values`).
|
640 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
641 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
642 |
+
Indices depicting the position of the input sequence tokens in the sequence.
|
643 |
+
kwargs (`dict`, *optional*):
|
644 |
+
Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
|
645 |
+
into the model
|
646 |
+
"""
|
647 |
+
|
648 |
+
residual = hidden_states
|
649 |
+
|
650 |
+
hidden_states = self.input_layernorm(hidden_states)
|
651 |
+
|
652 |
+
# Self Attention
|
653 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
654 |
+
hidden_states=hidden_states,
|
655 |
+
attention_mask=attention_mask,
|
656 |
+
position_ids=position_ids,
|
657 |
+
past_key_value=past_key_value,
|
658 |
+
output_attentions=output_attentions,
|
659 |
+
use_cache=use_cache,
|
660 |
+
cache_position=cache_position,
|
661 |
+
)
|
662 |
+
hidden_states = residual + hidden_states
|
663 |
+
|
664 |
+
# Fully Connected
|
665 |
+
residual = hidden_states
|
666 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
667 |
+
hidden_states = self.mlp(hidden_states)
|
668 |
+
hidden_states = residual + hidden_states
|
669 |
+
|
670 |
+
outputs = (hidden_states,)
|
671 |
+
|
672 |
+
if output_attentions:
|
673 |
+
outputs += (self_attn_weights,)
|
674 |
+
|
675 |
+
if use_cache:
|
676 |
+
outputs += (present_key_value,)
|
677 |
+
|
678 |
+
return outputs
|
679 |
+
|
680 |
+
|
681 |
+
QWEN2_START_DOCSTRING = r"""
|
682 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
683 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
684 |
+
etc.)
|
685 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
686 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
687 |
+
and behavior.
|
688 |
+
Parameters:
|
689 |
+
config ([`Qwen2Config`]):
|
690 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
691 |
+
load the weights associated with the model, only the configuration. Check out the
|
692 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
693 |
+
"""
|
694 |
+
|
695 |
+
|
696 |
+
@add_start_docstrings(
|
697 |
+
"The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
|
698 |
+
QWEN2_START_DOCSTRING,
|
699 |
+
)
|
700 |
+
class Qwen2PreTrainedModel(PreTrainedModel):
|
701 |
+
config_class = Qwen2Config
|
702 |
+
base_model_prefix = "model"
|
703 |
+
supports_gradient_checkpointing = True
|
704 |
+
_no_split_modules = ["Qwen2DecoderLayer"]
|
705 |
+
_skip_keys_device_placement = "past_key_values"
|
706 |
+
_supports_flash_attn_2 = True
|
707 |
+
_supports_sdpa = True
|
708 |
+
_supports_cache_class = True
|
709 |
+
|
710 |
+
def _init_weights(self, module):
|
711 |
+
std = self.config.initializer_range
|
712 |
+
if isinstance(module, nn.Linear):
|
713 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
714 |
+
if module.bias is not None:
|
715 |
+
module.bias.data.zero_()
|
716 |
+
elif isinstance(module, nn.Embedding):
|
717 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
718 |
+
if module.padding_idx is not None:
|
719 |
+
module.weight.data[module.padding_idx].zero_()
|
720 |
+
|
721 |
+
|
722 |
+
QWEN2_INPUTS_DOCSTRING = r"""
|
723 |
+
Args:
|
724 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
725 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
726 |
+
it.
|
727 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
728 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
729 |
+
[What are input IDs?](../glossary#input-ids)
|
730 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
731 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
732 |
+
- 1 for tokens that are **not masked**,
|
733 |
+
- 0 for tokens that are **masked**.
|
734 |
+
[What are attention masks?](../glossary#attention-mask)
|
735 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
736 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
737 |
+
If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
738 |
+
`past_key_values`).
|
739 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
740 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
741 |
+
information on the default strategy.
|
742 |
+
- 1 indicates the head is **not masked**,
|
743 |
+
- 0 indicates the head is **masked**.
|
744 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
745 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
746 |
+
config.n_positions - 1]`.
|
747 |
+
[What are position IDs?](../glossary#position-ids)
|
748 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
749 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
750 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
751 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
752 |
+
Two formats are allowed:
|
753 |
+
- a [`~cache_utils.Cache`] instance;
|
754 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
755 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
756 |
+
cache format.
|
757 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
758 |
+
legacy cache format will be returned.
|
759 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
760 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
761 |
+
of shape `(batch_size, sequence_length)`.
|
762 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
763 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
764 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
765 |
+
model's internal embedding lookup matrix.
|
766 |
+
use_cache (`bool`, *optional*):
|
767 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
768 |
+
`past_key_values`).
|
769 |
+
output_attentions (`bool`, *optional*):
|
770 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
771 |
+
tensors for more detail.
|
772 |
+
output_hidden_states (`bool`, *optional*):
|
773 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
774 |
+
more detail.
|
775 |
+
return_dict (`bool`, *optional*):
|
776 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
777 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
778 |
+
Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
|
779 |
+
this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
|
780 |
+
the complete sequence length.
|
781 |
+
"""
|
782 |
+
|
783 |
+
|
784 |
+
@add_start_docstrings(
|
785 |
+
"The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
|
786 |
+
QWEN2_START_DOCSTRING,
|
787 |
+
)
|
788 |
+
class Qwen2Model(Qwen2PreTrainedModel):
|
789 |
+
"""
|
790 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
|
791 |
+
Args:
|
792 |
+
config: Qwen2Config
|
793 |
+
"""
|
794 |
+
|
795 |
+
def __init__(self, config: Qwen2Config):
|
796 |
+
super().__init__(config)
|
797 |
+
self.padding_idx = config.pad_token_id
|
798 |
+
self.vocab_size = config.vocab_size
|
799 |
+
|
800 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
801 |
+
self.layers = nn.ModuleList(
|
802 |
+
[Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
803 |
+
)
|
804 |
+
self._attn_implementation = config._attn_implementation
|
805 |
+
self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
806 |
+
|
807 |
+
self.gradient_checkpointing = False
|
808 |
+
# Initialize weights and apply final processing
|
809 |
+
self.post_init()
|
810 |
+
|
811 |
+
def get_input_embeddings(self):
|
812 |
+
return self.embed_tokens
|
813 |
+
|
814 |
+
def set_input_embeddings(self, value):
|
815 |
+
self.embed_tokens = value
|
816 |
+
|
817 |
+
@add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
|
818 |
+
def forward(
|
819 |
+
self,
|
820 |
+
input_ids: torch.LongTensor = None,
|
821 |
+
attention_mask: Optional[torch.Tensor] = None,
|
822 |
+
position_ids: Optional[torch.LongTensor] = None,
|
823 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
824 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
825 |
+
use_cache: Optional[bool] = None,
|
826 |
+
output_attentions: Optional[bool] = None,
|
827 |
+
output_hidden_states: Optional[bool] = None,
|
828 |
+
return_dict: Optional[bool] = None,
|
829 |
+
cache_position: Optional[torch.LongTensor] = None,
|
830 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
831 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
832 |
+
output_hidden_states = (
|
833 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
834 |
+
)
|
835 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
836 |
+
|
837 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
838 |
+
|
839 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
840 |
+
raise ValueError(
|
841 |
+
"You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
|
842 |
+
)
|
843 |
+
|
844 |
+
if self.gradient_checkpointing and self.training:
|
845 |
+
if use_cache:
|
846 |
+
logger.warning_once(
|
847 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
848 |
+
)
|
849 |
+
use_cache = False
|
850 |
+
|
851 |
+
use_legacy_cache = False
|
852 |
+
if use_cache and not isinstance(past_key_values, Cache) and not self.training:
|
853 |
+
use_legacy_cache = True
|
854 |
+
past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
855 |
+
logger.warning_once(
|
856 |
+
"We detected that you are passing `past_key_values` as a tuple and this is deprecated and will be removed in v4.43. "
|
857 |
+
"Please use an appropriate `Cache` class (https://huggingface.co/docs/transformers/v4.41.3/en/internal/generation_utils#transformers.Cache)"
|
858 |
+
)
|
859 |
+
|
860 |
+
if inputs_embeds is None:
|
861 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
862 |
+
|
863 |
+
if cache_position is None:
|
864 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
865 |
+
cache_position = torch.arange(
|
866 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
867 |
+
)
|
868 |
+
if position_ids is None:
|
869 |
+
position_ids = cache_position.unsqueeze(0)
|
870 |
+
|
871 |
+
causal_mask = self._update_causal_mask(
|
872 |
+
attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
|
873 |
+
)
|
874 |
+
|
875 |
+
hidden_states = inputs_embeds
|
876 |
+
|
877 |
+
# decoder layers
|
878 |
+
all_hidden_states = () if output_hidden_states else None
|
879 |
+
all_self_attns = () if output_attentions else None
|
880 |
+
next_decoder_cache = None
|
881 |
+
|
882 |
+
for decoder_layer in self.layers:
|
883 |
+
if output_hidden_states:
|
884 |
+
all_hidden_states += (hidden_states,)
|
885 |
+
|
886 |
+
if self.gradient_checkpointing and self.training:
|
887 |
+
layer_outputs = self._gradient_checkpointing_func(
|
888 |
+
decoder_layer.__call__,
|
889 |
+
hidden_states,
|
890 |
+
causal_mask,
|
891 |
+
position_ids,
|
892 |
+
past_key_values,
|
893 |
+
output_attentions,
|
894 |
+
use_cache,
|
895 |
+
cache_position,
|
896 |
+
)
|
897 |
+
else:
|
898 |
+
layer_outputs = decoder_layer(
|
899 |
+
hidden_states,
|
900 |
+
attention_mask=causal_mask,
|
901 |
+
position_ids=position_ids,
|
902 |
+
past_key_value=past_key_values,
|
903 |
+
output_attentions=output_attentions,
|
904 |
+
use_cache=use_cache,
|
905 |
+
cache_position=cache_position,
|
906 |
+
)
|
907 |
+
|
908 |
+
hidden_states = layer_outputs[0]
|
909 |
+
|
910 |
+
if use_cache:
|
911 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
912 |
+
|
913 |
+
if output_attentions:
|
914 |
+
all_self_attns += (layer_outputs[1],)
|
915 |
+
|
916 |
+
hidden_states = self.norm(hidden_states)
|
917 |
+
|
918 |
+
# add hidden states from the last decoder layer
|
919 |
+
if output_hidden_states:
|
920 |
+
all_hidden_states += (hidden_states,)
|
921 |
+
|
922 |
+
next_cache = None
|
923 |
+
if use_cache:
|
924 |
+
next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
|
925 |
+
|
926 |
+
if not return_dict:
|
927 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
928 |
+
return BaseModelOutputWithPast(
|
929 |
+
last_hidden_state=hidden_states,
|
930 |
+
past_key_values=next_cache,
|
931 |
+
hidden_states=all_hidden_states,
|
932 |
+
attentions=all_self_attns,
|
933 |
+
)
|
934 |
+
|
935 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaModel._update_causal_mask
|
936 |
+
def _update_causal_mask(
|
937 |
+
self,
|
938 |
+
attention_mask: torch.Tensor,
|
939 |
+
input_tensor: torch.Tensor,
|
940 |
+
cache_position: torch.Tensor,
|
941 |
+
past_key_values: Cache,
|
942 |
+
output_attentions: bool,
|
943 |
+
):
|
944 |
+
# TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
|
945 |
+
# KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
|
946 |
+
# (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
|
947 |
+
# `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
|
948 |
+
|
949 |
+
if self.config._attn_implementation == "flash_attention_2":
|
950 |
+
if attention_mask is not None and 0.0 in attention_mask:
|
951 |
+
return attention_mask
|
952 |
+
return None
|
953 |
+
|
954 |
+
# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
|
955 |
+
# order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
|
956 |
+
# to infer the attention mask.
|
957 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
958 |
+
using_static_cache = False#isinstance(past_key_values, StaticCache)
|
959 |
+
|
960 |
+
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
|
961 |
+
if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
|
962 |
+
if AttentionMaskConverter._ignore_causal_mask_sdpa(
|
963 |
+
attention_mask,
|
964 |
+
inputs_embeds=input_tensor,
|
965 |
+
past_key_values_length=past_seen_tokens,
|
966 |
+
is_training=self.training,
|
967 |
+
):
|
968 |
+
return None
|
969 |
+
|
970 |
+
dtype, device = input_tensor.dtype, input_tensor.device
|
971 |
+
min_dtype = torch.finfo(dtype).min
|
972 |
+
sequence_length = input_tensor.shape[1]
|
973 |
+
if using_static_cache:
|
974 |
+
target_length = past_key_values.get_max_length()
|
975 |
+
else:
|
976 |
+
target_length = (
|
977 |
+
attention_mask.shape[-1]
|
978 |
+
if isinstance(attention_mask, torch.Tensor)
|
979 |
+
else past_seen_tokens + sequence_length + 1
|
980 |
+
)
|
981 |
+
|
982 |
+
# In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
|
983 |
+
causal_mask = _prepare_4d_causal_attention_mask_with_cache_position(
|
984 |
+
attention_mask,
|
985 |
+
sequence_length=sequence_length,
|
986 |
+
target_length=target_length,
|
987 |
+
dtype=dtype,
|
988 |
+
device=device,
|
989 |
+
min_dtype=min_dtype,
|
990 |
+
cache_position=cache_position,
|
991 |
+
batch_size=input_tensor.shape[0],
|
992 |
+
)
|
993 |
+
|
994 |
+
if (
|
995 |
+
self.config._attn_implementation == "sdpa"
|
996 |
+
and attention_mask is not None
|
997 |
+
and attention_mask.device.type == "cuda"
|
998 |
+
and not output_attentions
|
999 |
+
):
|
1000 |
+
# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
|
1001 |
+
# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
|
1002 |
+
# Details: https://github.com/pytorch/pytorch/issues/110213
|
1003 |
+
causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
|
1004 |
+
|
1005 |
+
return causal_mask
|
1006 |
+
|
1007 |
+
|
1008 |
+
class Qwen2ForCausalLM(Qwen2PreTrainedModel):
|
1009 |
+
_tied_weights_keys = ["lm_head.weight"]
|
1010 |
+
|
1011 |
+
def __init__(self, config):
|
1012 |
+
super().__init__(config)
|
1013 |
+
self.model = Qwen2Model(config)
|
1014 |
+
self.vocab_size = config.vocab_size
|
1015 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
1016 |
+
|
1017 |
+
# Initialize weights and apply final processing
|
1018 |
+
self.post_init()
|
1019 |
+
|
1020 |
+
def get_input_embeddings(self):
|
1021 |
+
return self.model.embed_tokens
|
1022 |
+
|
1023 |
+
def set_input_embeddings(self, value):
|
1024 |
+
self.model.embed_tokens = value
|
1025 |
+
|
1026 |
+
def get_output_embeddings(self):
|
1027 |
+
return self.lm_head
|
1028 |
+
|
1029 |
+
def set_output_embeddings(self, new_embeddings):
|
1030 |
+
self.lm_head = new_embeddings
|
1031 |
+
|
1032 |
+
def set_decoder(self, decoder):
|
1033 |
+
self.model = decoder
|
1034 |
+
|
1035 |
+
def get_decoder(self):
|
1036 |
+
return self.model
|
1037 |
+
|
1038 |
+
@add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
|
1039 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
1040 |
+
def forward(
|
1041 |
+
self,
|
1042 |
+
input_ids: torch.LongTensor = None,
|
1043 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1044 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1045 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1046 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1047 |
+
labels: Optional[torch.LongTensor] = None,
|
1048 |
+
use_cache: Optional[bool] = None,
|
1049 |
+
output_attentions: Optional[bool] = None,
|
1050 |
+
output_hidden_states: Optional[bool] = None,
|
1051 |
+
return_dict: Optional[bool] = None,
|
1052 |
+
cache_position: Optional[torch.LongTensor] = None,
|
1053 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
1054 |
+
r"""
|
1055 |
+
Args:
|
1056 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1057 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
1058 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
1059 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
1060 |
+
Returns:
|
1061 |
+
Example:
|
1062 |
+
```python
|
1063 |
+
>>> from transformers import AutoTokenizer, Qwen2ForCausalLM
|
1064 |
+
>>> model = Qwen2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
|
1065 |
+
>>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
|
1066 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
1067 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
1068 |
+
>>> # Generate
|
1069 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
1070 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
1071 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
1072 |
+
```"""
|
1073 |
+
|
1074 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1075 |
+
output_hidden_states = (
|
1076 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1077 |
+
)
|
1078 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1079 |
+
|
1080 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
1081 |
+
outputs = self.model(
|
1082 |
+
input_ids=input_ids,
|
1083 |
+
attention_mask=attention_mask,
|
1084 |
+
position_ids=position_ids,
|
1085 |
+
past_key_values=past_key_values,
|
1086 |
+
inputs_embeds=inputs_embeds,
|
1087 |
+
use_cache=use_cache,
|
1088 |
+
output_attentions=output_attentions,
|
1089 |
+
output_hidden_states=output_hidden_states,
|
1090 |
+
return_dict=return_dict,
|
1091 |
+
cache_position=cache_position,
|
1092 |
+
)
|
1093 |
+
|
1094 |
+
hidden_states = outputs[0]
|
1095 |
+
logits = self.lm_head(hidden_states)
|
1096 |
+
logits = logits.float()
|
1097 |
+
|
1098 |
+
loss = None
|
1099 |
+
if labels is not None:
|
1100 |
+
# Shift so that tokens < n predict n
|
1101 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
1102 |
+
shift_labels = labels[..., 1:].contiguous()
|
1103 |
+
# Flatten the tokens
|
1104 |
+
loss_fct = CrossEntropyLoss()
|
1105 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
1106 |
+
shift_labels = shift_labels.view(-1)
|
1107 |
+
# Enable model parallelism
|
1108 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
1109 |
+
loss = loss_fct(shift_logits, shift_labels)
|
1110 |
+
|
1111 |
+
if not return_dict:
|
1112 |
+
output = (logits,) + outputs[1:]
|
1113 |
+
return (loss,) + output if loss is not None else output
|
1114 |
+
|
1115 |
+
return CausalLMOutputWithPast(
|
1116 |
+
loss=loss,
|
1117 |
+
logits=logits,
|
1118 |
+
past_key_values=outputs.past_key_values,
|
1119 |
+
hidden_states=outputs.hidden_states,
|
1120 |
+
attentions=outputs.attentions,
|
1121 |
+
)
|
1122 |
+
|
1123 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.prepare_inputs_for_generation
|
1124 |
+
def prepare_inputs_for_generation(
|
1125 |
+
self,
|
1126 |
+
input_ids,
|
1127 |
+
past_key_values=None,
|
1128 |
+
attention_mask=None,
|
1129 |
+
inputs_embeds=None,
|
1130 |
+
cache_position=None,
|
1131 |
+
position_ids=None,
|
1132 |
+
use_cache=True,
|
1133 |
+
**kwargs,
|
1134 |
+
):
|
1135 |
+
# If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
|
1136 |
+
# Exception 1: when passing input_embeds, input_ids may be missing entries
|
1137 |
+
# Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
|
1138 |
+
if past_key_values is not None:
|
1139 |
+
if inputs_embeds is not None: # Exception 1
|
1140 |
+
input_ids = input_ids[:, -cache_position.shape[0] :]
|
1141 |
+
elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
|
1142 |
+
input_ids = input_ids[:, cache_position]
|
1143 |
+
|
1144 |
+
if attention_mask is not None and position_ids is None:
|
1145 |
+
# create position_ids on the fly for batch generation
|
1146 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
1147 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
1148 |
+
if past_key_values:
|
1149 |
+
position_ids = position_ids[:, -input_ids.shape[1] :]
|
1150 |
+
|
1151 |
+
# This `clone` call is needed to avoid recapturing cuda graphs with `torch.compile`'s `mode="reduce-overhead`, as otherwise the input `position_ids` would have various stride during the decoding. Here, simply using `.contiguous()` is not sufficient as in the batch size = 1 case, `position_ids` is already contiguous but with varying stride which retriggers a capture.
|
1152 |
+
position_ids = position_ids.clone(memory_format=torch.contiguous_format)
|
1153 |
+
|
1154 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
1155 |
+
if inputs_embeds is not None and cache_position[0] == 0:
|
1156 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
1157 |
+
else:
|
1158 |
+
model_inputs = {"input_ids": input_ids}
|
1159 |
+
|
1160 |
+
if False and isinstance(past_key_values, StaticCache) and attention_mask.ndim == 2:
|
1161 |
+
if inputs_embeds is not None:
|
1162 |
+
batch_size, sequence_length = inputs_embeds.shape
|
1163 |
+
device = inputs_embeds.device
|
1164 |
+
else:
|
1165 |
+
batch_size, sequence_length = input_ids.shape
|
1166 |
+
device = input_ids.device
|
1167 |
+
|
1168 |
+
dtype = self.lm_head.weight.dtype
|
1169 |
+
min_dtype = torch.finfo(dtype).min
|
1170 |
+
|
1171 |
+
attention_mask = _prepare_4d_causal_attention_mask_with_cache_position(
|
1172 |
+
attention_mask,
|
1173 |
+
sequence_length=sequence_length,
|
1174 |
+
target_length=past_key_values.get_max_length(),
|
1175 |
+
dtype=dtype,
|
1176 |
+
device=device,
|
1177 |
+
min_dtype=min_dtype,
|
1178 |
+
cache_position=cache_position,
|
1179 |
+
batch_size=batch_size,
|
1180 |
+
)
|
1181 |
+
|
1182 |
+
model_inputs.update(
|
1183 |
+
{
|
1184 |
+
"position_ids": position_ids,
|
1185 |
+
"cache_position": cache_position,
|
1186 |
+
"past_key_values": past_key_values,
|
1187 |
+
"use_cache": use_cache,
|
1188 |
+
"attention_mask": attention_mask,
|
1189 |
+
}
|
1190 |
+
)
|
1191 |
+
return model_inputs
|
1192 |
+
|
1193 |
+
|
1194 |
+
@add_start_docstrings(
|
1195 |
+
"""
|
1196 |
+
The Qwen2 Model transformer with a sequence classification head on top (linear layer).
|
1197 |
+
[`Qwen2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
1198 |
+
(e.g. GPT-2) do.
|
1199 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
1200 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
1201 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
1202 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
1203 |
+
each row of the batch).
|
1204 |
+
""",
|
1205 |
+
QWEN2_START_DOCSTRING,
|
1206 |
+
)
|
1207 |
+
class Qwen2ForSequenceClassification(Qwen2PreTrainedModel):
|
1208 |
+
def __init__(self, config):
|
1209 |
+
super().__init__(config)
|
1210 |
+
self.num_labels = config.num_labels
|
1211 |
+
self.model = Qwen2Model(config)
|
1212 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
1213 |
+
|
1214 |
+
# Initialize weights and apply final processing
|
1215 |
+
self.post_init()
|
1216 |
+
|
1217 |
+
def get_input_embeddings(self):
|
1218 |
+
return self.model.embed_tokens
|
1219 |
+
|
1220 |
+
def set_input_embeddings(self, value):
|
1221 |
+
self.model.embed_tokens = value
|
1222 |
+
|
1223 |
+
@add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
|
1224 |
+
def forward(
|
1225 |
+
self,
|
1226 |
+
input_ids: torch.LongTensor = None,
|
1227 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1228 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1229 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1230 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1231 |
+
labels: Optional[torch.LongTensor] = None,
|
1232 |
+
use_cache: Optional[bool] = None,
|
1233 |
+
output_attentions: Optional[bool] = None,
|
1234 |
+
output_hidden_states: Optional[bool] = None,
|
1235 |
+
return_dict: Optional[bool] = None,
|
1236 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
1237 |
+
r"""
|
1238 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1239 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1240 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1241 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1242 |
+
"""
|
1243 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1244 |
+
|
1245 |
+
transformer_outputs = self.model(
|
1246 |
+
input_ids,
|
1247 |
+
attention_mask=attention_mask,
|
1248 |
+
position_ids=position_ids,
|
1249 |
+
past_key_values=past_key_values,
|
1250 |
+
inputs_embeds=inputs_embeds,
|
1251 |
+
use_cache=use_cache,
|
1252 |
+
output_attentions=output_attentions,
|
1253 |
+
output_hidden_states=output_hidden_states,
|
1254 |
+
return_dict=return_dict,
|
1255 |
+
)
|
1256 |
+
hidden_states = transformer_outputs[0]
|
1257 |
+
logits = self.score(hidden_states)
|
1258 |
+
|
1259 |
+
if input_ids is not None:
|
1260 |
+
batch_size = input_ids.shape[0]
|
1261 |
+
else:
|
1262 |
+
batch_size = inputs_embeds.shape[0]
|
1263 |
+
|
1264 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
1265 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
1266 |
+
if self.config.pad_token_id is None:
|
1267 |
+
sequence_lengths = -1
|
1268 |
+
else:
|
1269 |
+
if input_ids is not None:
|
1270 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
1271 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
1272 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
1273 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
1274 |
+
else:
|
1275 |
+
sequence_lengths = -1
|
1276 |
+
|
1277 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
1278 |
+
|
1279 |
+
loss = None
|
1280 |
+
if labels is not None:
|
1281 |
+
labels = labels.to(logits.device)
|
1282 |
+
if self.config.problem_type is None:
|
1283 |
+
if self.num_labels == 1:
|
1284 |
+
self.config.problem_type = "regression"
|
1285 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
1286 |
+
self.config.problem_type = "single_label_classification"
|
1287 |
+
else:
|
1288 |
+
self.config.problem_type = "multi_label_classification"
|
1289 |
+
|
1290 |
+
if self.config.problem_type == "regression":
|
1291 |
+
loss_fct = MSELoss()
|
1292 |
+
if self.num_labels == 1:
|
1293 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
1294 |
+
else:
|
1295 |
+
loss = loss_fct(pooled_logits, labels)
|
1296 |
+
elif self.config.problem_type == "single_label_classification":
|
1297 |
+
loss_fct = CrossEntropyLoss()
|
1298 |
+
loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
|
1299 |
+
elif self.config.problem_type == "multi_label_classification":
|
1300 |
+
loss_fct = BCEWithLogitsLoss()
|
1301 |
+
loss = loss_fct(pooled_logits, labels)
|
1302 |
+
if not return_dict:
|
1303 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
1304 |
+
return ((loss,) + output) if loss is not None else output
|
1305 |
+
|
1306 |
+
return SequenceClassifierOutputWithPast(
|
1307 |
+
loss=loss,
|
1308 |
+
logits=pooled_logits,
|
1309 |
+
past_key_values=transformer_outputs.past_key_values,
|
1310 |
+
hidden_states=transformer_outputs.hidden_states,
|
1311 |
+
attentions=transformer_outputs.attentions,
|
1312 |
+
)
|
1313 |
+
|
1314 |
+
|
1315 |
+
@add_start_docstrings(
|
1316 |
+
"""
|
1317 |
+
The Qwen2 Model transformer with a token classification head on top (a linear layer on top of the hidden-states
|
1318 |
+
output) e.g. for Named-Entity-Recognition (NER) tasks.
|
1319 |
+
""",
|
1320 |
+
QWEN2_START_DOCSTRING,
|
1321 |
+
)
|
1322 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForTokenClassification with Llama->Qwen2, LLAMA->QWEN2
|
1323 |
+
class Qwen2ForTokenClassification(Qwen2PreTrainedModel):
|
1324 |
+
def __init__(self, config):
|
1325 |
+
super().__init__(config)
|
1326 |
+
self.num_labels = config.num_labels
|
1327 |
+
self.model = Qwen2Model(config)
|
1328 |
+
if getattr(config, "classifier_dropout", None) is not None:
|
1329 |
+
classifier_dropout = config.classifier_dropout
|
1330 |
+
elif getattr(config, "hidden_dropout", None) is not None:
|
1331 |
+
classifier_dropout = config.hidden_dropout
|
1332 |
+
else:
|
1333 |
+
classifier_dropout = 0.1
|
1334 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
1335 |
+
self.score = nn.Linear(config.hidden_size, config.num_labels)
|
1336 |
+
|
1337 |
+
# Initialize weights and apply final processing
|
1338 |
+
self.post_init()
|
1339 |
+
|
1340 |
+
def get_input_embeddings(self):
|
1341 |
+
return self.model.embed_tokens
|
1342 |
+
|
1343 |
+
def set_input_embeddings(self, value):
|
1344 |
+
self.model.embed_tokens = value
|
1345 |
+
|
1346 |
+
@add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
|
1347 |
+
def forward(
|
1348 |
+
self,
|
1349 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1350 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1351 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1352 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1353 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1354 |
+
labels: Optional[torch.LongTensor] = None,
|
1355 |
+
use_cache: Optional[bool] = None,
|
1356 |
+
output_attentions: Optional[bool] = None,
|
1357 |
+
output_hidden_states: Optional[bool] = None,
|
1358 |
+
return_dict: Optional[bool] = None,
|
1359 |
+
) -> Union[Tuple, TokenClassifierOutput]:
|
1360 |
+
r"""
|
1361 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1362 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1363 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1364 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1365 |
+
"""
|
1366 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1367 |
+
|
1368 |
+
outputs = self.model(
|
1369 |
+
input_ids,
|
1370 |
+
attention_mask=attention_mask,
|
1371 |
+
position_ids=position_ids,
|
1372 |
+
past_key_values=past_key_values,
|
1373 |
+
inputs_embeds=inputs_embeds,
|
1374 |
+
use_cache=use_cache,
|
1375 |
+
output_attentions=output_attentions,
|
1376 |
+
output_hidden_states=output_hidden_states,
|
1377 |
+
return_dict=return_dict,
|
1378 |
+
)
|
1379 |
+
sequence_output = outputs[0]
|
1380 |
+
sequence_output = self.dropout(sequence_output)
|
1381 |
+
logits = self.score(sequence_output)
|
1382 |
+
|
1383 |
+
loss = None
|
1384 |
+
if labels is not None:
|
1385 |
+
loss_fct = CrossEntropyLoss()
|
1386 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
1387 |
+
|
1388 |
+
if not return_dict:
|
1389 |
+
output = (logits,) + outputs[2:]
|
1390 |
+
return ((loss,) + output) if loss is not None else output
|
1391 |
+
|
1392 |
+
return TokenClassifierOutput(
|
1393 |
+
loss=loss,
|
1394 |
+
logits=logits,
|
1395 |
+
hidden_states=outputs.hidden_states,
|
1396 |
+
attentions=outputs.attentions,
|
1397 |
+
)
|
1398 |
+
|
1399 |
+
|
1400 |
+
class ValueHead(nn.Module):
|
1401 |
+
r"""
|
1402 |
+
The ValueHead class implements a head for GPT2 that returns a scalar for each output token.
|
1403 |
+
"""
|
1404 |
+
|
1405 |
+
def __init__(self, config, **kwargs):
|
1406 |
+
super().__init__()
|
1407 |
+
if not hasattr(config, "summary_dropout_prob"):
|
1408 |
+
summary_dropout_prob = kwargs.pop("summary_dropout_prob", 0.1)
|
1409 |
+
else:
|
1410 |
+
summary_dropout_prob = config.summary_dropout_prob
|
1411 |
+
|
1412 |
+
self.dropout = nn.Dropout(summary_dropout_prob) if summary_dropout_prob else nn.Identity()
|
1413 |
+
|
1414 |
+
# some models such as OPT have a projection layer before the word embeddings - e.g. OPT-350m
|
1415 |
+
if hasattr(config, "hidden_size"):
|
1416 |
+
hidden_size = config.hidden_size
|
1417 |
+
|
1418 |
+
self.summary = nn.Linear(hidden_size, 1)
|
1419 |
+
|
1420 |
+
self.flatten = nn.Flatten()
|
1421 |
+
|
1422 |
+
def forward(self, hidden_states):
|
1423 |
+
output = self.dropout(hidden_states)
|
1424 |
+
|
1425 |
+
# For now force upcast in fp32 if needed. Let's keep the
|
1426 |
+
# output in fp32 for numerical stability.
|
1427 |
+
if output.dtype != self.summary.weight.dtype:
|
1428 |
+
output = output.to(self.summary.weight.dtype)
|
1429 |
+
|
1430 |
+
output = self.summary(output)
|
1431 |
+
return output
|
1432 |
+
|
1433 |
+
|
1434 |
+
@add_start_docstrings(
|
1435 |
+
"""
|
1436 |
+
The Qwen2 Model transformer with a sequence classification head on top (linear layer).
|
1437 |
+
[`Qwen2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
1438 |
+
(e.g. GPT-2) do.
|
1439 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
1440 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
1441 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
1442 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
1443 |
+
each row of the batch).
|
1444 |
+
""",
|
1445 |
+
QWEN2_START_DOCSTRING,
|
1446 |
+
)
|
1447 |
+
class Qwen2ForRewardModel(Qwen2PreTrainedModel):
|
1448 |
+
def __init__(self, config):
|
1449 |
+
super().__init__(config)
|
1450 |
+
self.num_labels = 1#config.num_labels
|
1451 |
+
self.model = Qwen2Model(config)
|
1452 |
+
# self.score = nn.Sequential(
|
1453 |
+
# nn.Linear(config.hidden_size, config.hidden_size),
|
1454 |
+
# nn.ReLU(),
|
1455 |
+
# nn.Linear(config.hidden_size, self.num_labels)
|
1456 |
+
# )
|
1457 |
+
self.v_head = ValueHead(config)
|
1458 |
+
|
1459 |
+
# Initialize weights and apply final processing
|
1460 |
+
self.post_init()
|
1461 |
+
|
1462 |
+
def get_input_embeddings(self):
|
1463 |
+
return self.model.embed_tokens
|
1464 |
+
|
1465 |
+
def set_input_embeddings(self, value):
|
1466 |
+
self.model.embed_tokens = value
|
1467 |
+
|
1468 |
+
@add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
|
1469 |
+
def forward(
|
1470 |
+
self,
|
1471 |
+
input_ids: torch.LongTensor = None,
|
1472 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1473 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1474 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1475 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1476 |
+
labels: Optional[torch.LongTensor] = None,
|
1477 |
+
use_cache: Optional[bool] = None,
|
1478 |
+
output_attentions: Optional[bool] = None,
|
1479 |
+
output_hidden_states: Optional[bool] = None,
|
1480 |
+
return_dict: Optional[bool] = None,
|
1481 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
1482 |
+
r"""
|
1483 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1484 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1485 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1486 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1487 |
+
"""
|
1488 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1489 |
+
transformer_outputs = self.model(
|
1490 |
+
input_ids,
|
1491 |
+
attention_mask=attention_mask,
|
1492 |
+
position_ids=position_ids,
|
1493 |
+
past_key_values=past_key_values,
|
1494 |
+
inputs_embeds=inputs_embeds,
|
1495 |
+
use_cache=use_cache,
|
1496 |
+
output_attentions=output_attentions,
|
1497 |
+
output_hidden_states=output_hidden_states,
|
1498 |
+
return_dict=return_dict,
|
1499 |
+
)
|
1500 |
+
hidden_states = transformer_outputs[0]
|
1501 |
+
# logits = self.score(hidden_states)
|
1502 |
+
logits = self.v_head(hidden_states).squeeze(-1)
|
1503 |
+
|
1504 |
+
if input_ids is not None:
|
1505 |
+
batch_size = input_ids.shape[0]
|
1506 |
+
else:
|
1507 |
+
batch_size = inputs_embeds.shape[0]
|
1508 |
+
|
1509 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
1510 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
1511 |
+
if self.config.pad_token_id is None:
|
1512 |
+
sequence_lengths = -1
|
1513 |
+
else:
|
1514 |
+
if input_ids is not None:
|
1515 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
1516 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
1517 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
1518 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
1519 |
+
else:
|
1520 |
+
sequence_lengths = -1
|
1521 |
+
|
1522 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
1523 |
+
|
1524 |
+
loss = None
|
1525 |
+
if labels is not None:
|
1526 |
+
labels = labels.to(logits.device)
|
1527 |
+
if self.config.problem_type is None:
|
1528 |
+
if self.num_labels == 1:
|
1529 |
+
self.config.problem_type = "regression"
|
1530 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
1531 |
+
self.config.problem_type = "single_label_classification"
|
1532 |
+
else:
|
1533 |
+
self.config.problem_type = "multi_label_classification"
|
1534 |
+
|
1535 |
+
if self.config.problem_type == "regression":
|
1536 |
+
loss_fct = MSELoss()
|
1537 |
+
if self.num_labels == 1:
|
1538 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
1539 |
+
else:
|
1540 |
+
loss = loss_fct(pooled_logits, labels)
|
1541 |
+
elif self.config.problem_type == "single_label_classification":
|
1542 |
+
loss_fct = CrossEntropyLoss()
|
1543 |
+
loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
|
1544 |
+
elif self.config.problem_type == "multi_label_classification":
|
1545 |
+
loss_fct = BCEWithLogitsLoss()
|
1546 |
+
loss = loss_fct(pooled_logits, labels)
|
1547 |
+
if not return_dict:
|
1548 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
1549 |
+
return ((loss,) + output) if loss is not None else output
|
1550 |
+
|
1551 |
+
return SequenceClassifierOutputWithPast(
|
1552 |
+
loss=loss,
|
1553 |
+
logits=pooled_logits,
|
1554 |
+
past_key_values=transformer_outputs.past_key_values,
|
1555 |
+
hidden_states=transformer_outputs.hidden_states,
|
1556 |
+
attentions=transformer_outputs.attentions,
|
1557 |
+
)
|
pytorch_model.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c1de1109b83e4835855daf766ae4281bd1be38a0a4fd165820b5a3a1498d3ceb
|
3 |
+
size 3087498236
|
special_tokens_map.json
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
"bos_token": "<|im_start|>",
|
18 |
+
"eos_token": {
|
19 |
+
"content": "<|im_end|>",
|
20 |
+
"lstrip": false,
|
21 |
+
"normalized": false,
|
22 |
+
"rstrip": false,
|
23 |
+
"single_word": false
|
24 |
+
},
|
25 |
+
"pad_token": {
|
26 |
+
"content": "<|endoftext|>",
|
27 |
+
"lstrip": false,
|
28 |
+
"normalized": false,
|
29 |
+
"rstrip": false,
|
30 |
+
"single_word": false
|
31 |
+
}
|
32 |
+
}
|
tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
tokenizer_config.json
ADDED
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
},
|
182 |
+
"additional_special_tokens": [
|
183 |
+
"<|im_start|>",
|
184 |
+
"<|im_end|>",
|
185 |
+
"<|object_ref_start|>",
|
186 |
+
"<|object_ref_end|>",
|
187 |
+
"<|box_start|>",
|
188 |
+
"<|box_end|>",
|
189 |
+
"<|quad_start|>",
|
190 |
+
"<|quad_end|>",
|
191 |
+
"<|vision_start|>",
|
192 |
+
"<|vision_end|>",
|
193 |
+
"<|vision_pad|>",
|
194 |
+
"<|image_pad|>",
|
195 |
+
"<|video_pad|>"
|
196 |
+
],
|
197 |
+
"bos_token": "<|im_start|>",
|
198 |
+
"chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0]['role'] == 'system' %}\n {{- messages[0]['content'] }}\n {%- else %}\n {{- 'Please reason step by step, and put your final answer within \\\\boxed{}.' }}\n {%- endif %}\n {{- \"\\n\\n# 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>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\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\" }}\n{%- else %}\n {%- if messages[0]['role'] == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0]['content'] + '<|im_end|>\\n' }}\n {%- else %}\n {{- '<|im_start|>system\\nPlease reason step by step, and put your final answer within \\\\boxed{}.<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- for message in messages %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) or (message.role == \"assistant\" and not message.tool_calls) %}\n {{- '<|im_start|>' + message.role + '\\n' + message.content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {{- '<|im_start|>' + message.role }}\n {%- if message.content %}\n {{- '\\n' + message.content }}\n {%- endif %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '\\n<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {{- tool_call.arguments | tojson }}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- message.content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n{%- endif %}\n",
|
199 |
+
"clean_up_tokenization_spaces": false,
|
200 |
+
"eos_token": "<|im_end|>",
|
201 |
+
"errors": "replace",
|
202 |
+
"model_max_length": 1000000000.0,
|
203 |
+
"pad_token": "<|endoftext|>",
|
204 |
+
"split_special_tokens": false,
|
205 |
+
"tokenizer_class": "Qwen2Tokenizer",
|
206 |
+
"unk_token": null
|
207 |
+
}
|
vocab.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|