hywu
/

Text Generation
Transformers
Safetensors
English
qwen2idae
conversational
custom_code
Inference Endpoints
4 papers
hywu commited on
Commit
e350fd8
1 Parent(s): 65d4253

upload qwen2idae

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