JO-KU commited on
Commit
b6ec373
·
verified ·
1 Parent(s): 5669bbf
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
config.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "GeoUniForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "modeling_geouni.GeoUniConfig",
7
+ "AutoModelForCausalLM": "modeling_geouni.GeoUniForCausalLM"
8
+ },
9
+ "attention_dropout": 0.0,
10
+ "bos_token_id": 151643,
11
+ "codebook_size": 8192,
12
+ "eos_token_id": 151643,
13
+ "hidden_act": "silu",
14
+ "hidden_size": 1536,
15
+ "initializer_range": 0.02,
16
+ "intermediate_size": 8960,
17
+ "llm_vocab_size": 151665,
18
+ "max_position_embeddings": 131072,
19
+ "max_window_layers": 21,
20
+ "model_type": "geo-uni",
21
+ "num_attention_heads": 12,
22
+ "num_hidden_layers": 28,
23
+ "num_key_value_heads": 2,
24
+ "num_new_special_tokens": 10,
25
+ "num_vq_tokens": 256,
26
+ "rms_norm_eps": 1e-06,
27
+ "rope_theta": 10000,
28
+ "sliding_window": 4096,
29
+ "tie_word_embeddings": false,
30
+ "torch_dtype": "bfloat16",
31
+ "transformers_version": "4.49.0",
32
+ "use_cache": true,
33
+ "use_mrope": false,
34
+ "use_sliding_window": false,
35
+ "vocab_size": 159867
36
+ }
configuration_qwen2.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Qwen2Config(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
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+
35
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 151936):
37
+ Vocabulary size of the Qwen2 model. Defines the number of different tokens that can be represented by the
38
+ `inputs_ids` passed when calling [`Qwen2Model`]
39
+ hidden_size (`int`, *optional*, defaults to 4096):
40
+ Dimension of the hidden representations.
41
+ intermediate_size (`int`, *optional*, defaults to 22016):
42
+ Dimension of the MLP representations.
43
+ num_hidden_layers (`int`, *optional*, defaults to 32):
44
+ Number of hidden layers in the Transformer encoder.
45
+ num_attention_heads (`int`, *optional*, defaults to 32):
46
+ Number of attention heads for each attention layer in the Transformer encoder.
47
+ num_key_value_heads (`int`, *optional*, defaults to 32):
48
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
49
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
50
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
51
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
52
+ by meanpooling all the original heads within that group. For more details checkout [this
53
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
54
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
55
+ The non-linear activation function (function or string) in the decoder.
56
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
57
+ The maximum sequence length that this model might ever be used with.
58
+ initializer_range (`float`, *optional*, defaults to 0.02):
59
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
60
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
61
+ The epsilon used by the rms normalization layers.
62
+ use_cache (`bool`, *optional*, defaults to `True`):
63
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
64
+ relevant if `config.is_decoder=True`.
65
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
66
+ Whether the model's input and output word embeddings should be tied.
67
+ rope_theta (`float`, *optional*, defaults to 10000.0):
68
+ The base period of the RoPE embeddings.
69
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
70
+ Whether to use sliding window attention.
71
+ sliding_window (`int`, *optional*, defaults to 4096):
72
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
73
+ max_window_layers (`int`, *optional*, defaults to 28):
74
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
75
+ attention_dropout (`float`, *optional*, defaults to 0.0):
76
+ The dropout ratio for the attention probabilities.
77
+
78
+ ```python
79
+ >>> from transformers import Qwen2Model, Qwen2Config
80
+
81
+ >>> # Initializing a Qwen2 style configuration
82
+ >>> configuration = Qwen2Config()
83
+
84
+ >>> # Initializing a model from the Qwen2-7B style configuration
85
+ >>> model = Qwen2Model(configuration)
86
+
87
+ >>> # Accessing the model configuration
88
+ >>> configuration = model.config
89
+ ```"""
90
+
91
+ model_type = "qwen2"
92
+ keys_to_ignore_at_inference = ["past_key_values"]
93
+
94
+ def __init__(
95
+ self,
96
+ vocab_size=151936,
97
+ hidden_size=4096,
98
+ intermediate_size=22016,
99
+ num_hidden_layers=32,
100
+ num_attention_heads=32,
101
+ num_key_value_heads=32,
102
+ hidden_act="silu",
103
+ max_position_embeddings=32768,
104
+ initializer_range=0.02,
105
+ rms_norm_eps=1e-6,
106
+ use_cache=True,
107
+ tie_word_embeddings=False,
108
+ rope_theta=10000.0,
109
+ use_sliding_window=False,
110
+ sliding_window=4096,
111
+ max_window_layers=28,
112
+ attention_dropout=0.0,
113
+ **kwargs,
114
+ ):
115
+ self.vocab_size = vocab_size
116
+ self.max_position_embeddings = max_position_embeddings
117
+ self.hidden_size = hidden_size
118
+ self.intermediate_size = intermediate_size
119
+ self.num_hidden_layers = num_hidden_layers
120
+ self.num_attention_heads = num_attention_heads
121
+ self.use_sliding_window = use_sliding_window
122
+ self.sliding_window = sliding_window
123
+ self.max_window_layers = max_window_layers
124
+
125
+ # for backward compatibility
126
+ if num_key_value_heads is None:
127
+ num_key_value_heads = num_attention_heads
128
+
129
+ self.num_key_value_heads = num_key_value_heads
130
+ self.hidden_act = hidden_act
131
+ self.initializer_range = initializer_range
132
+ self.rms_norm_eps = rms_norm_eps
133
+ self.use_cache = use_cache
134
+ self.rope_theta = rope_theta
135
+ self.attention_dropout = attention_dropout
136
+
137
+ super().__init__(
138
+ tie_word_embeddings=tie_word_embeddings,
139
+ **kwargs,
140
+ )
generation_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 151646,
4
+ "do_sample": true,
5
+ "eos_token_id": 151643,
6
+ "temperature": 0.6,
7
+ "top_p": 0.95,
8
+ "transformers_version": "4.49.0"
9
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5473091c3f343cf5d001fe2333196fa749e744808f824040c88567983c5b2bef
3
+ size 3602942824
modeling_geouni.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ import torch.nn as nn
4
+ from transformers import AutoConfig, AutoModelForCausalLM
5
+ from typing import List, Optional, Tuple, Union
6
+ from .modeling_qwen2 import Qwen2Model, Qwen2ForCausalLM
7
+ from .configuration_qwen2 import Qwen2Config
8
+
9
+
10
+ # Custom config for GeoUni
11
+ class GeoUniConfig(Qwen2Config):
12
+ model_type = "geo-uni"
13
+
14
+ def __init__(self, vocab_size=159864, num_vq_tokens=256, num_new_special_tokens=7, llm_vocab_size=151665, codebook_size=8192, **kwargs):
15
+ super().__init__(**kwargs) # Call parent class constructor
16
+ self.vocab_size = vocab_size
17
+ self.num_vq_tokens = num_vq_tokens
18
+ self.num_new_special_tokens = num_new_special_tokens
19
+ self.llm_vocab_size = llm_vocab_size
20
+ self.codebook_size = codebook_size
21
+
22
+
23
+ class GeoUniModel(Qwen2Model):
24
+ config_class = GeoUniConfig
25
+
26
+ def __init__(self, config: Qwen2Config):
27
+ super(GeoUniModel, self).__init__(config)
28
+
29
+
30
+ class GeoUniForCausalLM(Qwen2ForCausalLM):
31
+ config_class = GeoUniConfig
32
+
33
+ def __init__(self, config):
34
+ super(Qwen2ForCausalLM, self).__init__(config)
35
+ self.model = GeoUniModel(config)
36
+ self.vocab_size = config.vocab_size
37
+ self.num_vq_tokens = config.num_vq_tokens
38
+ self.num_new_special_tokens = config.num_new_special_tokens
39
+ self.llm_vocab_size = config.llm_vocab_size
40
+ self.codebook_size = config.codebook_size
41
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
42
+
43
+ # Initialize weights and apply final processing
44
+ self.post_init()
45
+
46
+ def get_model(self):
47
+ return self.model
48
+
49
+ def forward(
50
+ self,
51
+ input_ids: torch.LongTensor = None,
52
+ attention_mask: Optional[torch.Tensor] = None,
53
+ position_ids: Optional[torch.LongTensor] = None,
54
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
55
+ inputs_embeds: Optional[torch.FloatTensor] = None,
56
+ labels: Optional[torch.LongTensor] = None,
57
+ use_cache: Optional[bool] = None,
58
+ output_attentions: Optional[bool] = None,
59
+ output_hidden_states: Optional[bool] = None,
60
+ return_dict: Optional[bool] = None,
61
+ batch_size_t2i=0,
62
+ batch_size_reasoning=0,
63
+ batch_size_mixing=0,
64
+ ):
65
+ outputs = super().forward(input_ids, attention_mask, position_ids, past_key_values, inputs_embeds, labels, use_cache, output_attentions, output_hidden_states, return_dict)
66
+ if labels is not None:
67
+ logits = outputs.logits
68
+ loss_t2i = F.cross_entropy(
69
+ logits[:batch_size_t2i, :-1].contiguous().view(-1, self.vocab_size),
70
+ labels[:batch_size_t2i, 1:].contiguous().view(-1), ignore_index=-100,
71
+ )
72
+ loss_reasoning = F.cross_entropy(
73
+ logits[batch_size_t2i:batch_size_t2i+batch_size_reasoning, :-1].contiguous().view(-1, self.vocab_size),
74
+ labels[batch_size_t2i:batch_size_t2i+batch_size_reasoning, 1:].contiguous().view(-1), ignore_index=-100,
75
+ )
76
+ loss_mixing = F.cross_entropy(
77
+ logits[-batch_size_mixing:, :-1].contiguous().view(-1, self.vocab_size),
78
+ labels[-batch_size_mixing:, 1:].contiguous().view(-1), ignore_index=-100,
79
+ )
80
+
81
+ return logits, loss_t2i, loss_reasoning, loss_mixing
82
+
83
+ return outputs
84
+
85
+ @torch.no_grad()
86
+ def t2i_generate(
87
+ self,
88
+ input_ids: torch.LongTensor,
89
+ pad_token_id=151665,
90
+ temperature=1.0,
91
+ attention_masks=None,
92
+ ):
93
+
94
+
95
+ # 生成 num_vq_tokens 个新 token
96
+ generated_tokens = self.generate(input_ids=input_ids,
97
+ max_new_tokens=self.num_vq_tokens,
98
+ attention_mask=attention_masks,
99
+ pad_token_id=pad_token_id,
100
+ eos_token_id=None,
101
+ temperature=temperature,
102
+ do_sample=False,
103
+ top_p=None,
104
+ use_cache=True,
105
+ )
106
+
107
+ # 转换为 VQ-GAN 可接收的 token
108
+ new_tokens = generated_tokens[:, -self.num_vq_tokens:] - (self.llm_vocab_size + self.num_new_special_tokens)
109
+ gen_token_ids = torch.clamp(new_tokens, max=self.codebook_size - 1, min=0)
110
+
111
+ return gen_token_ids
112
+
113
+ @torch.no_grad()
114
+ def mix_generate(self,
115
+ input_ids,
116
+ max_new_tokens: int,
117
+ temperature: float,
118
+ pad_token_id: int,
119
+ eos_token_id: int,
120
+ soi_token_id: int,
121
+ eoi_token_id: int) -> Tuple[List[torch.Tensor], List[torch.Tensor]]:
122
+
123
+ # 生成完整序列
124
+ output_ids = self.generate(
125
+ input_ids=input_ids,
126
+ max_new_tokens=max_new_tokens,
127
+ temperature=temperature,
128
+ pad_token_id=pad_token_id,
129
+ eos_token_id=eos_token_id,
130
+ do_sample=False,
131
+ top_p=None,
132
+ use_cache=True
133
+ )
134
+ output_ids = output_ids[:, input_ids.size(1):] # 移除输入部分
135
+
136
+ batch_size = output_ids.size(0)
137
+ assert batch_size == 1
138
+ image_tokens = output_ids[:, 1:1+self.num_vq_tokens]
139
+ image_tokens = image_tokens - (self.llm_vocab_size + self.num_new_special_tokens)
140
+ pad_length = self.num_vq_tokens - image_tokens.shape[1]
141
+ # 如果不足,后面用0补齐
142
+ if pad_length > 0:
143
+ padding = torch.zeros((image_tokens.shape[0], pad_length), dtype=image_tokens.dtype, device=image_tokens.device)
144
+ image_tokens = torch.cat([image_tokens, padding], dim=1)
145
+ image_tokens = torch.clamp(image_tokens, max=self.codebook_size - 1, min=0)
146
+ text_tokens = output_ids[:, 2+self.num_vq_tokens:]
147
+ return image_tokens, text_tokens
148
+
149
+ AutoConfig.register("geo-uni", GeoUniConfig)
150
+ AutoModelForCausalLM.register(GeoUniConfig, GeoUniForCausalLM)
modeling_qwen2.py ADDED
@@ -0,0 +1,1404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch Qwen2 model."""
21
+ import inspect
22
+ import math
23
+ import warnings
24
+ from typing import List, Optional, Tuple, Union
25
+
26
+ import torch
27
+ import torch.nn.functional as F
28
+ import torch.utils.checkpoint
29
+ from torch import nn
30
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
31
+
32
+ from transformers.activations import ACT2FN
33
+ from transformers.cache_utils import Cache, DynamicCache
34
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa
35
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
36
+ from transformers.modeling_utils import PreTrainedModel
37
+ from transformers.utils import (
38
+ add_start_docstrings,
39
+ add_start_docstrings_to_model_forward,
40
+ is_flash_attn_2_available,
41
+ is_flash_attn_greater_or_equal_2_10,
42
+ logging,
43
+ replace_return_docstrings,
44
+ )
45
+ from .configuration_qwen2 import Qwen2Config
46
+
47
+
48
+ if is_flash_attn_2_available():
49
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
50
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
51
+
52
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
53
+
54
+
55
+ logger = logging.get_logger(__name__)
56
+
57
+
58
+ _CHECKPOINT_FOR_DOC = "Qwen/Qwen2-7B-beta"
59
+ _CONFIG_FOR_DOC = "Qwen2Config"
60
+
61
+ QWEN2_PRETRAINED_MODEL_ARCHIVE_LIST = [
62
+ "Qwen/Qwen2-7B-beta",
63
+ # See all Qwen2 models at https://huggingface.co/models?filter=qwen2
64
+ ]
65
+
66
+
67
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
68
+ def _get_unpad_data(attention_mask):
69
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
70
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
71
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
72
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
73
+ return (
74
+ indices,
75
+ cu_seqlens,
76
+ max_seqlen_in_batch,
77
+ )
78
+
79
+
80
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Qwen2
81
+ class Qwen2RMSNorm(nn.Module):
82
+ def __init__(self, hidden_size, eps=1e-6):
83
+ """
84
+ Qwen2RMSNorm is equivalent to T5LayerNorm
85
+ """
86
+ super().__init__()
87
+ self.weight = nn.Parameter(torch.ones(hidden_size))
88
+ self.variance_epsilon = eps
89
+
90
+ def forward(self, hidden_states):
91
+ input_dtype = hidden_states.dtype
92
+ hidden_states = hidden_states.to(torch.float32)
93
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
94
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
95
+ return self.weight * hidden_states.to(input_dtype)
96
+
97
+
98
+ # Copied from transformers.models.mistral.modeling_mistral.MistralRotaryEmbedding with Mistral->Qwen2
99
+ class Qwen2RotaryEmbedding(nn.Module):
100
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
101
+ super().__init__()
102
+
103
+ self.dim = dim
104
+ self.max_position_embeddings = max_position_embeddings
105
+ self.base = base
106
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
107
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
108
+
109
+ # Build here to make `torch.jit.trace` work.
110
+ self._set_cos_sin_cache(
111
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
112
+ )
113
+
114
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
115
+ self.max_seq_len_cached = seq_len
116
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
117
+
118
+ freqs = torch.outer(t, self.inv_freq)
119
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
120
+ emb = torch.cat((freqs, freqs), dim=-1)
121
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
122
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
123
+
124
+ def forward(self, x, seq_len=None):
125
+ # x: [bs, num_attention_heads, seq_len, head_size]
126
+ if seq_len > self.max_seq_len_cached:
127
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
128
+
129
+ return (
130
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
131
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
132
+ )
133
+
134
+
135
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
136
+ def rotate_half(x):
137
+ """Rotates half the hidden dims of the input."""
138
+ x1 = x[..., : x.shape[-1] // 2]
139
+ x2 = x[..., x.shape[-1] // 2 :]
140
+ return torch.cat((-x2, x1), dim=-1)
141
+
142
+
143
+ # Copied from transformers.models.mistral.modeling_mistral.apply_rotary_pos_emb
144
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
145
+ """Applies Rotary Position Embedding to the query and key tensors.
146
+
147
+ Args:
148
+ q (`torch.Tensor`): The query tensor.
149
+ k (`torch.Tensor`): The key tensor.
150
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
151
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
152
+ position_ids (`torch.Tensor`):
153
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
154
+ used to pass offsetted position ids when working with a KV-cache.
155
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
156
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
157
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
158
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
159
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
160
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
161
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
162
+ Returns:
163
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
164
+ """
165
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
166
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
167
+ q_embed = (q * cos) + (rotate_half(q) * sin)
168
+ k_embed = (k * cos) + (rotate_half(k) * sin)
169
+ return q_embed, k_embed
170
+
171
+
172
+ # Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Qwen2
173
+ class Qwen2MLP(nn.Module):
174
+ def __init__(self, config):
175
+ super().__init__()
176
+ self.config = config
177
+ self.hidden_size = config.hidden_size
178
+ self.intermediate_size = config.intermediate_size
179
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
180
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
181
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
182
+ self.act_fn = ACT2FN[config.hidden_act]
183
+
184
+ def forward(self, x):
185
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
186
+
187
+
188
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
189
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
190
+ """
191
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
192
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
193
+ """
194
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
195
+ if n_rep == 1:
196
+ return hidden_states
197
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
198
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
199
+
200
+
201
+ class Qwen2Attention(nn.Module):
202
+ """
203
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
204
+ and "Generating Long Sequences with Sparse Transformers".
205
+ """
206
+
207
+ def __init__(self, config: Qwen2Config, layer_idx: Optional[int] = None):
208
+ super().__init__()
209
+ self.config = config
210
+ self.layer_idx = layer_idx
211
+ if layer_idx is None:
212
+ logger.warning_once(
213
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
214
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
215
+ "when creating this class."
216
+ )
217
+
218
+ self.hidden_size = config.hidden_size
219
+ self.num_heads = config.num_attention_heads
220
+ self.head_dim = self.hidden_size // self.num_heads
221
+ self.num_key_value_heads = config.num_key_value_heads
222
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
223
+ self.max_position_embeddings = config.max_position_embeddings
224
+ self.rope_theta = config.rope_theta
225
+ self.is_causal = True
226
+ self.attention_dropout = config.attention_dropout
227
+
228
+ if (self.head_dim * self.num_heads) != self.hidden_size:
229
+ raise ValueError(
230
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
231
+ f" and `num_heads`: {self.num_heads})."
232
+ )
233
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
234
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
235
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
236
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
237
+
238
+ self.rotary_emb = Qwen2RotaryEmbedding(
239
+ self.head_dim,
240
+ max_position_embeddings=self.max_position_embeddings,
241
+ base=self.rope_theta,
242
+ )
243
+
244
+ def forward(
245
+ self,
246
+ hidden_states: torch.Tensor,
247
+ attention_mask: Optional[torch.Tensor] = None,
248
+ position_ids: Optional[torch.LongTensor] = None,
249
+ past_key_value: Optional[Cache] = None,
250
+ output_attentions: bool = False,
251
+ use_cache: bool = False,
252
+ **kwargs,
253
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
254
+ if "padding_mask" in kwargs:
255
+ warnings.warn(
256
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
257
+ )
258
+ bsz, q_len, _ = hidden_states.size()
259
+
260
+ query_states = self.q_proj(hidden_states)
261
+ key_states = self.k_proj(hidden_states)
262
+ value_states = self.v_proj(hidden_states)
263
+
264
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
265
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
266
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
267
+
268
+ kv_seq_len = key_states.shape[-2]
269
+ if past_key_value is not None:
270
+ if self.layer_idx is None:
271
+ raise ValueError(
272
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
273
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
274
+ "with a layer index."
275
+ )
276
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
277
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
278
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
279
+
280
+ if past_key_value is not None:
281
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
282
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
283
+
284
+ # repeat k/v heads if n_kv_heads < n_heads
285
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
286
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
287
+
288
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
289
+
290
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
291
+ raise ValueError(
292
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
293
+ f" {attn_weights.size()}"
294
+ )
295
+
296
+ if attention_mask is not None:
297
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
298
+ raise ValueError(
299
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
300
+ )
301
+
302
+ attn_weights = attn_weights + attention_mask
303
+
304
+ # upcast attention to fp32
305
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
306
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
307
+ attn_output = torch.matmul(attn_weights, value_states)
308
+
309
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
310
+ raise ValueError(
311
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
312
+ f" {attn_output.size()}"
313
+ )
314
+
315
+ attn_output = attn_output.transpose(1, 2).contiguous()
316
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
317
+
318
+ attn_output = self.o_proj(attn_output)
319
+
320
+ if not output_attentions:
321
+ attn_weights = None
322
+
323
+ return attn_output, attn_weights, past_key_value
324
+
325
+
326
+ class Qwen2FlashAttention2(Qwen2Attention):
327
+ """
328
+ Qwen2 flash attention module, following Qwen2 attention module. This module inherits from `Qwen2Attention`
329
+ as the weights of the module stays untouched. The only required change would be on the forward pass
330
+ where it needs to correctly call the public API of flash attention and deal with padding tokens
331
+ in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
332
+ config.max_window_layers layers.
333
+ """
334
+
335
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
336
+ def __init__(self, *args, **kwargs):
337
+ super().__init__(*args, **kwargs)
338
+
339
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
340
+ # 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.
341
+ # 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).
342
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
343
+
344
+ def forward(
345
+ self,
346
+ hidden_states: torch.Tensor,
347
+ attention_mask: Optional[torch.Tensor] = None,
348
+ position_ids: Optional[torch.LongTensor] = None,
349
+ past_key_value: Optional[Cache] = None,
350
+ output_attentions: bool = False,
351
+ use_cache: bool = False,
352
+ **kwargs,
353
+ ):
354
+ if "padding_mask" in kwargs:
355
+ warnings.warn(
356
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
357
+ )
358
+
359
+ # overwrite attention_mask with padding_mask
360
+ attention_mask = kwargs.pop("padding_mask")
361
+ bsz, q_len, _ = hidden_states.size()
362
+
363
+ query_states = self.q_proj(hidden_states)
364
+ key_states = self.k_proj(hidden_states)
365
+ value_states = self.v_proj(hidden_states)
366
+
367
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
368
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
369
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
370
+
371
+ kv_seq_len = key_states.shape[-2]
372
+ if past_key_value is not None:
373
+ if self.layer_idx is None:
374
+ raise ValueError(
375
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
376
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
377
+ "with a layer index."
378
+ )
379
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
380
+
381
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
382
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
383
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
384
+
385
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
386
+
387
+ use_sliding_windows = (
388
+ _flash_supports_window_size
389
+ and getattr(self.config, "sliding_window", None) is not None
390
+ and kv_seq_len > self.config.sliding_window
391
+ and self.config.use_sliding_window
392
+ )
393
+
394
+ if not _flash_supports_window_size:
395
+ logger.warning_once(
396
+ "The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
397
+ " make sure to upgrade flash-attn library."
398
+ )
399
+
400
+ if past_key_value is not None:
401
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
402
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
403
+ if (
404
+ getattr(self.config, "sliding_window", None) is not None
405
+ and kv_seq_len > self.config.sliding_window
406
+ and cache_has_contents
407
+ ):
408
+ slicing_tokens = 1 - self.config.sliding_window
409
+
410
+ past_key = past_key_value[self.layer_idx][0]
411
+ past_value = past_key_value[self.layer_idx][1]
412
+
413
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
414
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
415
+
416
+ if past_key.shape[-2] != self.config.sliding_window - 1:
417
+ raise ValueError(
418
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
419
+ f" {past_key.shape}"
420
+ )
421
+
422
+ if attention_mask is not None:
423
+ attention_mask = attention_mask[:, slicing_tokens:]
424
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
425
+
426
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
427
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
428
+
429
+ # repeat k/v heads if n_kv_heads < n_heads
430
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
431
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
432
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
433
+
434
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
435
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
436
+ # cast them back in float16 just to be sure everything works as expected.
437
+ input_dtype = query_states.dtype
438
+ if input_dtype == torch.float32:
439
+ if torch.is_autocast_enabled():
440
+ target_dtype = torch.get_autocast_gpu_dtype()
441
+ # Handle the case where the model is quantized
442
+ elif hasattr(self.config, "_pre_quantization_dtype"):
443
+ target_dtype = self.config._pre_quantization_dtype
444
+ else:
445
+ target_dtype = self.q_proj.weight.dtype
446
+
447
+ logger.warning_once(
448
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
449
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
450
+ f" {target_dtype}."
451
+ )
452
+
453
+ query_states = query_states.to(target_dtype)
454
+ key_states = key_states.to(target_dtype)
455
+ value_states = value_states.to(target_dtype)
456
+
457
+ # Reashape to the expected shape for Flash Attention
458
+ query_states = query_states.transpose(1, 2)
459
+ key_states = key_states.transpose(1, 2)
460
+ value_states = value_states.transpose(1, 2)
461
+
462
+ attn_output = self._flash_attention_forward(
463
+ query_states,
464
+ key_states,
465
+ value_states,
466
+ attention_mask,
467
+ q_len,
468
+ dropout=dropout_rate,
469
+ use_sliding_windows=use_sliding_windows,
470
+ )
471
+
472
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
473
+ attn_output = self.o_proj(attn_output)
474
+
475
+ if not output_attentions:
476
+ attn_weights = None
477
+
478
+ return attn_output, attn_weights, past_key_value
479
+
480
+ def _flash_attention_forward(
481
+ self,
482
+ query_states,
483
+ key_states,
484
+ value_states,
485
+ attention_mask,
486
+ query_length,
487
+ dropout=0.0,
488
+ softmax_scale=None,
489
+ use_sliding_windows=False,
490
+ ):
491
+ """
492
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
493
+ first unpad the input, then computes the attention scores and pad the final attention scores.
494
+
495
+ Args:
496
+ query_states (`torch.Tensor`):
497
+ Input query states to be passed to Flash Attention API
498
+ key_states (`torch.Tensor`):
499
+ Input key states to be passed to Flash Attention API
500
+ value_states (`torch.Tensor`):
501
+ Input value states to be passed to Flash Attention API
502
+ attention_mask (`torch.Tensor`):
503
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
504
+ position of padding tokens and 1 for the position of non-padding tokens.
505
+ dropout (`float`):
506
+ Attention dropout
507
+ softmax_scale (`float`, *optional*):
508
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
509
+ use_sliding_windows (`bool`, *optional*):
510
+ Whether to activate sliding window attention.
511
+ """
512
+ if not self._flash_attn_uses_top_left_mask:
513
+ causal = self.is_causal
514
+ else:
515
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
516
+ causal = self.is_causal and query_length != 1
517
+
518
+ # Decide whether to use SWA or not by layer index.
519
+ if use_sliding_windows and self.layer_idx >= self.config.max_window_layers:
520
+ use_sliding_windows = False
521
+
522
+ # Contains at least one padding token in the sequence
523
+ if attention_mask is not None:
524
+ batch_size = query_states.shape[0]
525
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
526
+ query_states, key_states, value_states, attention_mask, query_length
527
+ )
528
+
529
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
530
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
531
+
532
+ if not use_sliding_windows:
533
+ attn_output_unpad = flash_attn_varlen_func(
534
+ query_states,
535
+ key_states,
536
+ value_states,
537
+ cu_seqlens_q=cu_seqlens_q,
538
+ cu_seqlens_k=cu_seqlens_k,
539
+ max_seqlen_q=max_seqlen_in_batch_q,
540
+ max_seqlen_k=max_seqlen_in_batch_k,
541
+ dropout_p=dropout,
542
+ softmax_scale=softmax_scale,
543
+ causal=causal,
544
+ )
545
+ else:
546
+ attn_output_unpad = flash_attn_varlen_func(
547
+ query_states,
548
+ key_states,
549
+ value_states,
550
+ cu_seqlens_q=cu_seqlens_q,
551
+ cu_seqlens_k=cu_seqlens_k,
552
+ max_seqlen_q=max_seqlen_in_batch_q,
553
+ max_seqlen_k=max_seqlen_in_batch_k,
554
+ dropout_p=dropout,
555
+ softmax_scale=softmax_scale,
556
+ causal=causal,
557
+ window_size=(self.config.sliding_window, self.config.sliding_window),
558
+ )
559
+
560
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
561
+ else:
562
+ if not use_sliding_windows:
563
+ attn_output = flash_attn_func(
564
+ query_states,
565
+ key_states,
566
+ value_states,
567
+ dropout,
568
+ softmax_scale=softmax_scale,
569
+ causal=causal,
570
+ )
571
+ else:
572
+ attn_output = flash_attn_func(
573
+ query_states,
574
+ key_states,
575
+ value_states,
576
+ dropout,
577
+ softmax_scale=softmax_scale,
578
+ causal=causal,
579
+ window_size=(self.config.sliding_window, self.config.sliding_window),
580
+ )
581
+
582
+ return attn_output
583
+
584
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
585
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
586
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
587
+
588
+ # On the first iteration we need to properly re-create the padding mask
589
+ # by slicing it on the proper place
590
+ if kv_seq_len != attention_mask.shape[-1]:
591
+ attention_mask_num_tokens = attention_mask.shape[-1]
592
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
593
+
594
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
595
+
596
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
597
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
598
+
599
+ if query_length == kv_seq_len:
600
+ query_layer = index_first_axis(
601
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
602
+ )
603
+ cu_seqlens_q = cu_seqlens_k
604
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
605
+ indices_q = indices_k
606
+ elif query_length == 1:
607
+ max_seqlen_in_batch_q = 1
608
+ cu_seqlens_q = torch.arange(
609
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
610
+ ) # There is a memcpy here, that is very bad.
611
+ indices_q = cu_seqlens_q[:-1]
612
+ query_layer = query_layer.squeeze(1)
613
+ else:
614
+ # The -q_len: slice assumes left padding.
615
+ attention_mask = attention_mask[:, -query_length:]
616
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
617
+
618
+ return (
619
+ query_layer,
620
+ key_layer,
621
+ value_layer,
622
+ indices_q,
623
+ (cu_seqlens_q, cu_seqlens_k),
624
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
625
+ )
626
+
627
+
628
+ # Copied from transformers.models.mistral.modeling_mistral.MistralSdpaAttention with Mistral->Qwen2
629
+ class Qwen2SdpaAttention(Qwen2Attention):
630
+ """
631
+ Qwen2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
632
+ `Qwen2Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
633
+ SDPA API.
634
+ """
635
+
636
+ # Adapted from Qwen2Attention.forward
637
+ def forward(
638
+ self,
639
+ hidden_states: torch.Tensor,
640
+ attention_mask: Optional[torch.Tensor] = None,
641
+ position_ids: Optional[torch.LongTensor] = None,
642
+ past_key_value: Optional[Cache] = None,
643
+ output_attentions: bool = False,
644
+ use_cache: bool = False,
645
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
646
+ if output_attentions:
647
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
648
+ logger.warning_once(
649
+ "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, "
650
+ '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.'
651
+ )
652
+ return super().forward(
653
+ hidden_states=hidden_states,
654
+ attention_mask=attention_mask,
655
+ position_ids=position_ids,
656
+ past_key_value=past_key_value,
657
+ output_attentions=output_attentions,
658
+ use_cache=use_cache,
659
+ )
660
+
661
+ bsz, q_len, _ = hidden_states.size()
662
+
663
+ query_states = self.q_proj(hidden_states)
664
+ key_states = self.k_proj(hidden_states)
665
+ value_states = self.v_proj(hidden_states)
666
+
667
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
668
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
669
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
670
+
671
+ kv_seq_len = key_states.shape[-2]
672
+ if past_key_value is not None:
673
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
674
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
675
+
676
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
677
+
678
+ if past_key_value is not None:
679
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
680
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
681
+
682
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
683
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
684
+
685
+ if attention_mask is not None:
686
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
687
+ raise ValueError(
688
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
689
+ )
690
+
691
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
692
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
693
+ if query_states.device.type == "cuda" and attention_mask is not None:
694
+ query_states = query_states.contiguous()
695
+ key_states = key_states.contiguous()
696
+ value_states = value_states.contiguous()
697
+
698
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
699
+ query_states,
700
+ key_states,
701
+ value_states,
702
+ attn_mask=attention_mask,
703
+ dropout_p=self.attention_dropout if self.training else 0.0,
704
+ # 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.
705
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
706
+ )
707
+
708
+ attn_output = attn_output.transpose(1, 2).contiguous()
709
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
710
+
711
+ attn_output = self.o_proj(attn_output)
712
+
713
+ return attn_output, None, past_key_value
714
+
715
+
716
+ QWEN2_ATTENTION_CLASSES = {
717
+ "eager": Qwen2Attention,
718
+ "flash_attention_2": Qwen2FlashAttention2,
719
+ "sdpa": Qwen2SdpaAttention,
720
+ }
721
+
722
+
723
+ class Qwen2DecoderLayer(nn.Module):
724
+ def __init__(self, config: Qwen2Config, layer_idx: int):
725
+ super().__init__()
726
+ self.hidden_size = config.hidden_size
727
+
728
+ if config.use_sliding_window and config._attn_implementation != "flash_attention_2":
729
+ logger.warning_once(
730
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
731
+ "unexpected results may be encountered."
732
+ )
733
+ self.self_attn = QWEN2_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
734
+
735
+ self.mlp = Qwen2MLP(config)
736
+ self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
737
+ self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
738
+
739
+ def forward(
740
+ self,
741
+ hidden_states: torch.Tensor,
742
+ attention_mask: Optional[torch.Tensor] = None,
743
+ position_ids: Optional[torch.LongTensor] = None,
744
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
745
+ output_attentions: Optional[bool] = False,
746
+ use_cache: Optional[bool] = False,
747
+ **kwargs,
748
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
749
+ if "padding_mask" in kwargs:
750
+ warnings.warn(
751
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
752
+ "Please make sure use `attention_mask` instead.`"
753
+ )
754
+ """
755
+ Args:
756
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
757
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
758
+ `(batch, sequence_length)` where padding elements are indicated by 0.
759
+ output_attentions (`bool`, *optional*):
760
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
761
+ returned tensors for more detail.
762
+ use_cache (`bool`, *optional*):
763
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
764
+ (see `past_key_values`).
765
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
766
+ """
767
+
768
+ residual = hidden_states
769
+
770
+ hidden_states = self.input_layernorm(hidden_states)
771
+
772
+ # Self Attention
773
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
774
+ hidden_states=hidden_states,
775
+ attention_mask=attention_mask,
776
+ position_ids=position_ids,
777
+ past_key_value=past_key_value,
778
+ output_attentions=output_attentions,
779
+ use_cache=use_cache,
780
+ )
781
+ hidden_states = residual + hidden_states
782
+
783
+ # Fully Connected
784
+ residual = hidden_states
785
+ hidden_states = self.post_attention_layernorm(hidden_states)
786
+ hidden_states = self.mlp(hidden_states)
787
+ hidden_states = residual + hidden_states
788
+
789
+ outputs = (hidden_states,)
790
+
791
+ if output_attentions:
792
+ outputs += (self_attn_weights,)
793
+
794
+ if use_cache:
795
+ outputs += (present_key_value,)
796
+
797
+ return outputs
798
+
799
+
800
+ QWEN2_START_DOCSTRING = r"""
801
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
802
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
803
+ etc.)
804
+
805
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
806
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
807
+ and behavior.
808
+
809
+ Parameters:
810
+ config ([`Qwen2Config`]):
811
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
812
+ load the weights associated with the model, only the configuration. Check out the
813
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
814
+ """
815
+
816
+
817
+ @add_start_docstrings(
818
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
819
+ QWEN2_START_DOCSTRING,
820
+ )
821
+ class Qwen2PreTrainedModel(PreTrainedModel):
822
+ config_class = Qwen2Config
823
+ base_model_prefix = "model"
824
+ supports_gradient_checkpointing = True
825
+ _no_split_modules = ["Qwen2DecoderLayer"]
826
+ _skip_keys_device_placement = "past_key_values"
827
+ _supports_flash_attn_2 = True
828
+ _supports_sdpa = True
829
+ _supports_cache_class = True
830
+
831
+ def _init_weights(self, module):
832
+ std = self.config.initializer_range
833
+ if isinstance(module, nn.Linear):
834
+ module.weight.data.normal_(mean=0.0, std=std)
835
+ if module.bias is not None:
836
+ module.bias.data.zero_()
837
+ elif isinstance(module, nn.Embedding):
838
+ module.weight.data.normal_(mean=0.0, std=std)
839
+ if module.padding_idx is not None:
840
+ module.weight.data[module.padding_idx].zero_()
841
+
842
+
843
+ QWEN2_INPUTS_DOCSTRING = r"""
844
+ Args:
845
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
846
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
847
+ it.
848
+
849
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
850
+ [`PreTrainedTokenizer.__call__`] for details.
851
+
852
+ [What are input IDs?](../glossary#input-ids)
853
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
854
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
855
+
856
+ - 1 for tokens that are **not masked**,
857
+ - 0 for tokens that are **masked**.
858
+
859
+ [What are attention masks?](../glossary#attention-mask)
860
+
861
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
862
+ [`PreTrainedTokenizer.__call__`] for details.
863
+
864
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
865
+ `past_key_values`).
866
+
867
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
868
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
869
+ information on the default strategy.
870
+
871
+ - 1 indicates the head is **not masked**,
872
+ - 0 indicates the head is **masked**.
873
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
874
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
875
+ config.n_positions - 1]`.
876
+
877
+ [What are position IDs?](../glossary#position-ids)
878
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
879
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
880
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
881
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
882
+
883
+ Two formats are allowed:
884
+ - a [`~cache_utils.Cache`] instance;
885
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
886
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
887
+ cache format.
888
+
889
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
890
+ legacy cache format will be returned.
891
+
892
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
893
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
894
+ of shape `(batch_size, sequence_length)`.
895
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
896
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
897
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
898
+ model's internal embedding lookup matrix.
899
+ use_cache (`bool`, *optional*):
900
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
901
+ `past_key_values`).
902
+ output_attentions (`bool`, *optional*):
903
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
904
+ tensors for more detail.
905
+ output_hidden_states (`bool`, *optional*):
906
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
907
+ more detail.
908
+ return_dict (`bool`, *optional*):
909
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
910
+ """
911
+
912
+
913
+ @add_start_docstrings(
914
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
915
+ QWEN2_START_DOCSTRING,
916
+ )
917
+ class Qwen2Model(Qwen2PreTrainedModel):
918
+ """
919
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
920
+
921
+ Args:
922
+ config: Qwen2Config
923
+ """
924
+
925
+ def __init__(self, config: Qwen2Config):
926
+ super().__init__(config)
927
+ self.padding_idx = config.pad_token_id
928
+ self.vocab_size = config.vocab_size
929
+
930
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
931
+ self.layers = nn.ModuleList(
932
+ [Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
933
+ )
934
+ self._attn_implementation = config._attn_implementation
935
+ self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
936
+
937
+ self.gradient_checkpointing = False
938
+ # Initialize weights and apply final processing
939
+ self.post_init()
940
+
941
+ def get_input_embeddings(self):
942
+ return self.embed_tokens
943
+
944
+ def set_input_embeddings(self, value):
945
+ self.embed_tokens = value
946
+
947
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
948
+ def forward(
949
+ self,
950
+ input_ids: torch.LongTensor = None,
951
+ attention_mask: Optional[torch.Tensor] = None,
952
+ position_ids: Optional[torch.LongTensor] = None,
953
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
954
+ inputs_embeds: Optional[torch.FloatTensor] = None,
955
+ use_cache: Optional[bool] = None,
956
+ output_attentions: Optional[bool] = None,
957
+ output_hidden_states: Optional[bool] = None,
958
+ return_dict: Optional[bool] = None,
959
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
960
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
961
+ output_hidden_states = (
962
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
963
+ )
964
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
965
+
966
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
967
+
968
+ # retrieve input_ids and inputs_embeds
969
+ if input_ids is not None and inputs_embeds is not None:
970
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
971
+ elif input_ids is not None:
972
+ batch_size, seq_length = input_ids.shape
973
+ elif inputs_embeds is not None:
974
+ batch_size, seq_length, _ = inputs_embeds.shape
975
+ else:
976
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
977
+
978
+ if self.gradient_checkpointing and self.training:
979
+ if use_cache:
980
+ logger.warning_once(
981
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
982
+ )
983
+ use_cache = False
984
+
985
+ past_key_values_length = 0
986
+
987
+ if use_cache:
988
+ use_legacy_cache = not isinstance(past_key_values, Cache)
989
+ if use_legacy_cache:
990
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
991
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
992
+
993
+ if position_ids is None:
994
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
995
+ position_ids = torch.arange(
996
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
997
+ )
998
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
999
+ else:
1000
+ position_ids = position_ids.view(-1, seq_length).long()
1001
+
1002
+ if inputs_embeds is None:
1003
+ inputs_embeds = self.embed_tokens(input_ids)
1004
+
1005
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1006
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1007
+ if is_padding_right:
1008
+ raise ValueError(
1009
+ "You are attempting to perform batched generation with padding_side='right'"
1010
+ " this may lead to unexpected behaviour for Flash Attention version of Qwen2. Make sure to "
1011
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1012
+ )
1013
+
1014
+ if self._attn_implementation == "flash_attention_2":
1015
+ # 2d mask is passed through the layers
1016
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1017
+ elif self._attn_implementation == "sdpa" and not output_attentions:
1018
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1019
+ # the manual implementation that requires a 4D causal mask in all cases.
1020
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1021
+ attention_mask,
1022
+ (batch_size, seq_length),
1023
+ inputs_embeds,
1024
+ past_key_values_length,
1025
+ )
1026
+ else:
1027
+ # 4d mask is passed through the layers
1028
+ attention_mask = _prepare_4d_causal_attention_mask(
1029
+ attention_mask,
1030
+ (batch_size, seq_length),
1031
+ inputs_embeds,
1032
+ past_key_values_length,
1033
+ sliding_window=self.config.sliding_window,
1034
+ )
1035
+
1036
+ hidden_states = inputs_embeds
1037
+
1038
+ # decoder layers
1039
+ all_hidden_states = () if output_hidden_states else None
1040
+ all_self_attns = () if output_attentions else None
1041
+ next_decoder_cache = None
1042
+
1043
+ for decoder_layer in self.layers:
1044
+ if output_hidden_states:
1045
+ all_hidden_states += (hidden_states,)
1046
+
1047
+ if self.gradient_checkpointing and self.training:
1048
+ layer_outputs = self._gradient_checkpointing_func(
1049
+ decoder_layer.__call__,
1050
+ hidden_states,
1051
+ attention_mask,
1052
+ position_ids,
1053
+ past_key_values,
1054
+ output_attentions,
1055
+ use_cache,
1056
+ )
1057
+ else:
1058
+ layer_outputs = decoder_layer(
1059
+ hidden_states,
1060
+ attention_mask=attention_mask,
1061
+ position_ids=position_ids,
1062
+ past_key_value=past_key_values,
1063
+ output_attentions=output_attentions,
1064
+ use_cache=use_cache,
1065
+ )
1066
+
1067
+ hidden_states = layer_outputs[0]
1068
+
1069
+ if use_cache:
1070
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1071
+
1072
+ if output_attentions:
1073
+ all_self_attns += (layer_outputs[1],)
1074
+
1075
+ hidden_states = self.norm(hidden_states)
1076
+
1077
+ # add hidden states from the last decoder layer
1078
+ if output_hidden_states:
1079
+ all_hidden_states += (hidden_states,)
1080
+
1081
+ next_cache = None
1082
+ if use_cache:
1083
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1084
+
1085
+ if not return_dict:
1086
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1087
+ return BaseModelOutputWithPast(
1088
+ last_hidden_state=hidden_states,
1089
+ past_key_values=next_cache,
1090
+ hidden_states=all_hidden_states,
1091
+ attentions=all_self_attns,
1092
+ )
1093
+
1094
+
1095
+ class Qwen2ForCausalLM(Qwen2PreTrainedModel):
1096
+ _tied_weights_keys = ["lm_head.weight"]
1097
+
1098
+ def __init__(self, config):
1099
+ super().__init__(config)
1100
+ self.model = Qwen2Model(config)
1101
+ self.vocab_size = config.vocab_size
1102
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1103
+
1104
+ # Initialize weights and apply final processing
1105
+ self.post_init()
1106
+
1107
+ def get_input_embeddings(self):
1108
+ return self.model.embed_tokens
1109
+
1110
+ def set_input_embeddings(self, value):
1111
+ self.model.embed_tokens = value
1112
+
1113
+ def get_output_embeddings(self):
1114
+ return self.lm_head
1115
+
1116
+ def set_output_embeddings(self, new_embeddings):
1117
+ self.lm_head = new_embeddings
1118
+
1119
+ def set_decoder(self, decoder):
1120
+ self.model = decoder
1121
+
1122
+ def get_decoder(self):
1123
+ return self.model
1124
+
1125
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1126
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1127
+ def forward(
1128
+ self,
1129
+ input_ids: torch.LongTensor = None,
1130
+ attention_mask: Optional[torch.Tensor] = None,
1131
+ position_ids: Optional[torch.LongTensor] = None,
1132
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1133
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1134
+ labels: Optional[torch.LongTensor] = None,
1135
+ use_cache: Optional[bool] = None,
1136
+ output_attentions: Optional[bool] = None,
1137
+ output_hidden_states: Optional[bool] = None,
1138
+ return_dict: Optional[bool] = None,
1139
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1140
+ r"""
1141
+ Args:
1142
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1143
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1144
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1145
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1146
+
1147
+ Returns:
1148
+
1149
+ Example:
1150
+
1151
+ ```python
1152
+ >>> from transformers import AutoTokenizer, Qwen2ForCausalLM
1153
+
1154
+ >>> model = Qwen2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1155
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1156
+
1157
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1158
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1159
+
1160
+ >>> # Generate
1161
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1162
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1163
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1164
+ ```"""
1165
+
1166
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1167
+ output_hidden_states = (
1168
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1169
+ )
1170
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1171
+
1172
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1173
+ outputs = self.model(
1174
+ input_ids=input_ids,
1175
+ attention_mask=attention_mask,
1176
+ position_ids=position_ids,
1177
+ past_key_values=past_key_values,
1178
+ inputs_embeds=inputs_embeds,
1179
+ use_cache=use_cache,
1180
+ output_attentions=output_attentions,
1181
+ output_hidden_states=output_hidden_states,
1182
+ return_dict=return_dict,
1183
+ )
1184
+
1185
+ hidden_states = outputs[0]
1186
+ logits = self.lm_head(hidden_states)
1187
+ logits = logits.float()
1188
+
1189
+ loss = None
1190
+ if labels is not None:
1191
+ # Shift so that tokens < n predict n
1192
+ shift_logits = logits[..., :-1, :].contiguous()
1193
+ shift_labels = labels[..., 1:].contiguous()
1194
+ # Flatten the tokens
1195
+ loss_fct = CrossEntropyLoss()
1196
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1197
+ shift_labels = shift_labels.view(-1)
1198
+ # Enable model parallelism
1199
+ shift_labels = shift_labels.to(shift_logits.device)
1200
+ loss = loss_fct(shift_logits, shift_labels)
1201
+
1202
+ if not return_dict:
1203
+ output = (logits,) + outputs[1:]
1204
+ return (loss,) + output if loss is not None else output
1205
+
1206
+ return CausalLMOutputWithPast(
1207
+ loss=loss,
1208
+ logits=logits,
1209
+ past_key_values=outputs.past_key_values,
1210
+ hidden_states=outputs.hidden_states,
1211
+ attentions=outputs.attentions,
1212
+ )
1213
+
1214
+ def prepare_inputs_for_generation(
1215
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1216
+ ):
1217
+ # Omit tokens covered by past_key_values
1218
+ if past_key_values is not None:
1219
+ if isinstance(past_key_values, Cache):
1220
+ cache_length = past_key_values.get_seq_length()
1221
+ past_length = past_key_values.seen_tokens
1222
+ # max_cache_length = past_key_values.get_max_length()
1223
+ max_cache_length = past_key_values.get_max_cache_shape()
1224
+ else:
1225
+ cache_length = past_length = past_key_values[0][0].shape[2]
1226
+ max_cache_length = None
1227
+
1228
+ # Keep only the unprocessed tokens:
1229
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1230
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1231
+ # input)
1232
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1233
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1234
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1235
+ # input_ids based on the past_length.
1236
+ elif past_length < input_ids.shape[1]:
1237
+ input_ids = input_ids[:, past_length:]
1238
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1239
+ else:
1240
+ remove_prefix_length = input_ids.shape[1] - 1
1241
+ input_ids = input_ids[:, remove_prefix_length:]
1242
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1243
+ if (
1244
+ max_cache_length is not None
1245
+ and attention_mask is not None
1246
+ and cache_length + input_ids.shape[1] > max_cache_length
1247
+ ):
1248
+ attention_mask = attention_mask[:, -max_cache_length:]
1249
+
1250
+ position_ids = kwargs.get("position_ids", None)
1251
+ if attention_mask is not None and position_ids is None:
1252
+ # create position_ids on the fly for batch generation
1253
+ position_ids = attention_mask.long().cumsum(-1) - 1
1254
+ position_ids.masked_fill_(attention_mask == 0, 1)
1255
+ if past_key_values:
1256
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1257
+
1258
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1259
+ if inputs_embeds is not None and past_key_values is None:
1260
+ model_inputs = {"inputs_embeds": inputs_embeds}
1261
+ else:
1262
+ model_inputs = {"input_ids": input_ids}
1263
+
1264
+ model_inputs.update(
1265
+ {
1266
+ "position_ids": position_ids,
1267
+ "past_key_values": past_key_values,
1268
+ "use_cache": kwargs.get("use_cache"),
1269
+ "attention_mask": attention_mask,
1270
+ }
1271
+ )
1272
+ return model_inputs
1273
+
1274
+ @staticmethod
1275
+ def _reorder_cache(past_key_values, beam_idx):
1276
+ reordered_past = ()
1277
+ for layer_past in past_key_values:
1278
+ reordered_past += (
1279
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1280
+ )
1281
+ return reordered_past
1282
+
1283
+
1284
+ @add_start_docstrings(
1285
+ """
1286
+ The Qwen2 Model transformer with a sequence classification head on top (linear layer).
1287
+
1288
+ [`Qwen2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1289
+ (e.g. GPT-2) do.
1290
+
1291
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1292
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1293
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1294
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1295
+ each row of the batch).
1296
+ """,
1297
+ QWEN2_START_DOCSTRING,
1298
+ )
1299
+ class Qwen2ForSequenceClassification(Qwen2PreTrainedModel):
1300
+ def __init__(self, config):
1301
+ super().__init__(config)
1302
+ self.num_labels = config.num_labels
1303
+ self.model = Qwen2Model(config)
1304
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1305
+
1306
+ # Initialize weights and apply final processing
1307
+ self.post_init()
1308
+
1309
+ def get_input_embeddings(self):
1310
+ return self.model.embed_tokens
1311
+
1312
+ def set_input_embeddings(self, value):
1313
+ self.model.embed_tokens = value
1314
+
1315
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1316
+ def forward(
1317
+ self,
1318
+ input_ids: torch.LongTensor = None,
1319
+ attention_mask: Optional[torch.Tensor] = None,
1320
+ position_ids: Optional[torch.LongTensor] = None,
1321
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1322
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1323
+ labels: Optional[torch.LongTensor] = None,
1324
+ use_cache: Optional[bool] = None,
1325
+ output_attentions: Optional[bool] = None,
1326
+ output_hidden_states: Optional[bool] = None,
1327
+ return_dict: Optional[bool] = None,
1328
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1329
+ r"""
1330
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1331
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1332
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1333
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1334
+ """
1335
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1336
+
1337
+ transformer_outputs = self.model(
1338
+ input_ids,
1339
+ attention_mask=attention_mask,
1340
+ position_ids=position_ids,
1341
+ past_key_values=past_key_values,
1342
+ inputs_embeds=inputs_embeds,
1343
+ use_cache=use_cache,
1344
+ output_attentions=output_attentions,
1345
+ output_hidden_states=output_hidden_states,
1346
+ return_dict=return_dict,
1347
+ )
1348
+ hidden_states = transformer_outputs[0]
1349
+ logits = self.score(hidden_states)
1350
+
1351
+ if input_ids is not None:
1352
+ batch_size = input_ids.shape[0]
1353
+ else:
1354
+ batch_size = inputs_embeds.shape[0]
1355
+
1356
+ if self.config.pad_token_id is None and batch_size != 1:
1357
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1358
+ if self.config.pad_token_id is None:
1359
+ sequence_lengths = -1
1360
+ else:
1361
+ if input_ids is not None:
1362
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1363
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1364
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1365
+ sequence_lengths = sequence_lengths.to(logits.device)
1366
+ else:
1367
+ sequence_lengths = -1
1368
+
1369
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1370
+
1371
+ loss = None
1372
+ if labels is not None:
1373
+ labels = labels.to(logits.device)
1374
+ if self.config.problem_type is None:
1375
+ if self.num_labels == 1:
1376
+ self.config.problem_type = "regression"
1377
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1378
+ self.config.problem_type = "single_label_classification"
1379
+ else:
1380
+ self.config.problem_type = "multi_label_classification"
1381
+
1382
+ if self.config.problem_type == "regression":
1383
+ loss_fct = MSELoss()
1384
+ if self.num_labels == 1:
1385
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1386
+ else:
1387
+ loss = loss_fct(pooled_logits, labels)
1388
+ elif self.config.problem_type == "single_label_classification":
1389
+ loss_fct = CrossEntropyLoss()
1390
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1391
+ elif self.config.problem_type == "multi_label_classification":
1392
+ loss_fct = BCEWithLogitsLoss()
1393
+ loss = loss_fct(pooled_logits, labels)
1394
+ if not return_dict:
1395
+ output = (pooled_logits,) + transformer_outputs[1:]
1396
+ return ((loss,) + output) if loss is not None else output
1397
+
1398
+ return SequenceClassifierOutputWithPast(
1399
+ loss=loss,
1400
+ logits=pooled_logits,
1401
+ past_key_values=transformer_outputs.past_key_values,
1402
+ hidden_states=transformer_outputs.hidden_states,
1403
+ attentions=transformer_outputs.attentions,
1404
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|begin▁of▁sentence|>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|end▁of▁sentence|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "[PAD]",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ }
23
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4ef432a5d2299f6100647749d2efe4604027f7bdcbc4b4e5ebdba031a3649afa
3
+ size 11424636
tokenizer_config.json ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": null,
5
+ "added_tokens_decoder": {
6
+ "151643": {
7
+ "content": "<|end▁of▁sentence|>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "151644": {
15
+ "content": "<|User|>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": false
21
+ },
22
+ "151645": {
23
+ "content": "<|Assistant|>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "special": false
29
+ },
30
+ "151646": {
31
+ "content": "<|begin▁of▁sentence|>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false,
36
+ "special": true
37
+ },
38
+ "151647": {
39
+ "content": "<|EOT|>",
40
+ "lstrip": false,
41
+ "normalized": false,
42
+ "rstrip": false,
43
+ "single_word": false,
44
+ "special": false
45
+ },
46
+ "151648": {
47
+ "content": "<think>",
48
+ "lstrip": false,
49
+ "normalized": false,
50
+ "rstrip": false,
51
+ "single_word": false,
52
+ "special": false
53
+ },
54
+ "151649": {
55
+ "content": "</think>",
56
+ "lstrip": false,
57
+ "normalized": false,
58
+ "rstrip": false,
59
+ "single_word": false,
60
+ "special": false
61
+ },
62
+ "151650": {
63
+ "content": "<|quad_start|>",
64
+ "lstrip": false,
65
+ "normalized": false,
66
+ "rstrip": false,
67
+ "single_word": false,
68
+ "special": true
69
+ },
70
+ "151651": {
71
+ "content": "<|quad_end|>",
72
+ "lstrip": false,
73
+ "normalized": false,
74
+ "rstrip": false,
75
+ "single_word": false,
76
+ "special": true
77
+ },
78
+ "151652": {
79
+ "content": "<|vision_start|>",
80
+ "lstrip": false,
81
+ "normalized": false,
82
+ "rstrip": false,
83
+ "single_word": false,
84
+ "special": true
85
+ },
86
+ "151653": {
87
+ "content": "<|vision_end|>",
88
+ "lstrip": false,
89
+ "normalized": false,
90
+ "rstrip": false,
91
+ "single_word": false,
92
+ "special": true
93
+ },
94
+ "151654": {
95
+ "content": "<|vision_pad|>",
96
+ "lstrip": false,
97
+ "normalized": false,
98
+ "rstrip": false,
99
+ "single_word": false,
100
+ "special": true
101
+ },
102
+ "151655": {
103
+ "content": "<|image_pad|>",
104
+ "lstrip": false,
105
+ "normalized": false,
106
+ "rstrip": false,
107
+ "single_word": false,
108
+ "special": true
109
+ },
110
+ "151656": {
111
+ "content": "<|video_pad|>",
112
+ "lstrip": false,
113
+ "normalized": false,
114
+ "rstrip": false,
115
+ "single_word": false,
116
+ "special": true
117
+ },
118
+ "151657": {
119
+ "content": "<tool_call>",
120
+ "lstrip": false,
121
+ "normalized": false,
122
+ "rstrip": false,
123
+ "single_word": false,
124
+ "special": false
125
+ },
126
+ "151658": {
127
+ "content": "</tool_call>",
128
+ "lstrip": false,
129
+ "normalized": false,
130
+ "rstrip": false,
131
+ "single_word": false,
132
+ "special": false
133
+ },
134
+ "151659": {
135
+ "content": "<|fim_prefix|>",
136
+ "lstrip": false,
137
+ "normalized": false,
138
+ "rstrip": false,
139
+ "single_word": false,
140
+ "special": false
141
+ },
142
+ "151660": {
143
+ "content": "<|fim_middle|>",
144
+ "lstrip": false,
145
+ "normalized": false,
146
+ "rstrip": false,
147
+ "single_word": false,
148
+ "special": false
149
+ },
150
+ "151661": {
151
+ "content": "<|fim_suffix|>",
152
+ "lstrip": false,
153
+ "normalized": false,
154
+ "rstrip": false,
155
+ "single_word": false,
156
+ "special": false
157
+ },
158
+ "151662": {
159
+ "content": "<|fim_pad|>",
160
+ "lstrip": false,
161
+ "normalized": false,
162
+ "rstrip": false,
163
+ "single_word": false,
164
+ "special": false
165
+ },
166
+ "151663": {
167
+ "content": "<|repo_name|>",
168
+ "lstrip": false,
169
+ "normalized": false,
170
+ "rstrip": false,
171
+ "single_word": false,
172
+ "special": false
173
+ },
174
+ "151664": {
175
+ "content": "<|file_sep|>",
176
+ "lstrip": false,
177
+ "normalized": false,
178
+ "rstrip": false,
179
+ "single_word": false,
180
+ "special": false
181
+ },
182
+ "151665": {
183
+ "content": "[PAD]",
184
+ "lstrip": false,
185
+ "normalized": false,
186
+ "rstrip": false,
187
+ "single_word": false,
188
+ "special": true
189
+ },
190
+ "151666": {
191
+ "content": "<|soi|>",
192
+ "lstrip": false,
193
+ "normalized": true,
194
+ "rstrip": false,
195
+ "single_word": false,
196
+ "special": false
197
+ },
198
+ "151667": {
199
+ "content": "<|eoi|>",
200
+ "lstrip": false,
201
+ "normalized": true,
202
+ "rstrip": false,
203
+ "single_word": false,
204
+ "special": false
205
+ },
206
+ "151668": {
207
+ "content": "<|t2i|>",
208
+ "lstrip": false,
209
+ "normalized": true,
210
+ "rstrip": false,
211
+ "single_word": false,
212
+ "special": false
213
+ },
214
+ "151669": {
215
+ "content": "<|mmu|>",
216
+ "lstrip": false,
217
+ "normalized": true,
218
+ "rstrip": false,
219
+ "single_word": false,
220
+ "special": false
221
+ },
222
+ "151670": {
223
+ "content": "<|mix|>",
224
+ "lstrip": false,
225
+ "normalized": true,
226
+ "rstrip": false,
227
+ "single_word": false,
228
+ "special": false
229
+ },
230
+ "151671": {
231
+ "content": "<formalization>",
232
+ "lstrip": false,
233
+ "normalized": true,
234
+ "rstrip": false,
235
+ "single_word": false,
236
+ "special": false
237
+ },
238
+ "151672": {
239
+ "content": "</formalization>",
240
+ "lstrip": false,
241
+ "normalized": true,
242
+ "rstrip": false,
243
+ "single_word": false,
244
+ "special": false
245
+ },
246
+ "151673": {
247
+ "content": "<answer>",
248
+ "lstrip": false,
249
+ "normalized": true,
250
+ "rstrip": false,
251
+ "single_word": false,
252
+ "special": false
253
+ },
254
+ "151674": {
255
+ "content": "</answer>",
256
+ "lstrip": false,
257
+ "normalized": true,
258
+ "rstrip": false,
259
+ "single_word": false,
260
+ "special": false
261
+ }
262
+ },
263
+ "bos_token": "<|begin▁of▁sentence|>",
264
+ "chat_template": "{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{% set ns = namespace(is_first=false, is_tool=false, is_output_first=true, system_prompt='') %}{%- for message in messages %}{%- if message['role'] == 'system' %}{% set ns.system_prompt = message['content'] %}{%- endif %}{%- endfor %}{{bos_token}}{{ns.system_prompt}}{%- for message in messages %}{%- if message['role'] == 'user' %}{%- set ns.is_tool = false -%}{{'<|User|>' + message['content']}}{%- endif %}{%- if message['role'] == 'assistant' and message['content'] is none %}{%- set ns.is_tool = false -%}{%- for tool in message['tool_calls']%}{%- if not ns.is_first %}{{'<|Assistant|><|tool▁calls▁begin|><|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\\n' + '```json' + '\\n' + tool['function']['arguments'] + '\\n' + '```' + '<|tool▁call▁end|>'}}{%- set ns.is_first = true -%}{%- else %}{{'\\n' + '<|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\\n' + '```json' + '\\n' + tool['function']['arguments'] + '\\n' + '```' + '<|tool▁call▁end|>'}}{{'<|tool▁calls▁end|><|end▁of▁sentence|>'}}{%- endif %}{%- endfor %}{%- endif %}{%- if message['role'] == 'assistant' and message['content'] is not none %}{%- if ns.is_tool %}{{'<|tool▁outputs▁end|>' + message['content'] + '<|end▁of▁sentence|>'}}{%- set ns.is_tool = false -%}{%- else %}{% set content = message['content'] %}{% if '</think>' in content %}{% set content = content.split('</think>')[-1] %}{% endif %}{{'<|Assistant|>' + content + '<|end▁of▁sentence|>'}}{%- endif %}{%- endif %}{%- if message['role'] == 'tool' %}{%- set ns.is_tool = true -%}{%- if ns.is_output_first %}{{'<|tool▁outputs▁begin|><|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- set ns.is_output_first = false %}{%- else %}{{'\\n<|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- endif %}{%- endif %}{%- endfor -%}{% if ns.is_tool %}{{'<|tool▁outputs▁end|>'}}{% endif %}{% if add_generation_prompt and not ns.is_tool %}{{'<|Assistant|>'}}{% endif %}",
265
+ "clean_up_tokenization_spaces": false,
266
+ "eos_token": "<|end▁of▁sentence|>",
267
+ "extra_special_tokens": {},
268
+ "legacy": true,
269
+ "model_max_length": 16384,
270
+ "pad_token": "[PAD]",
271
+ "sp_model_kwargs": {},
272
+ "tokenizer_class": "LlamaTokenizerFast",
273
+ "unk_token": null,
274
+ "use_default_system_prompt": false
275
+ }