Mghao commited on
Commit
d0d996d
·
1 Parent(s): fbe5162

first commit

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