gangiswag commited on
Commit
b29bc35
·
verified ·
1 Parent(s): 6e42665

Upload folder using huggingface_hub

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