Upload folder using huggingface_hub
Browse files- Qwen2.5-3B-512k-lc-39iters/.ipynb_checkpoints/config-checkpoint.json +28 -0
- Qwen2.5-3B-512k-lc-39iters/config.json +33 -0
- Qwen2.5-3B-512k-lc-39iters/generation_config.json +7 -0
- Qwen2.5-3B-512k-lc-39iters/model-00001-of-00002.safetensors +3 -0
- Qwen2.5-3B-512k-lc-39iters/model-00002-of-00002.safetensors +3 -0
- Qwen2.5-3B-512k-lc-39iters/model.safetensors.index.json +441 -0
- Qwen2.5-3B-512k-lc-39iters/modeling_qwen2.py +1136 -0
- Qwen2.5-3B-512k-lc-39iters/tokenizer.json +0 -0
- Qwen2.5-3B-512k-lc-39iters/tokenizer_config.json +207 -0
- Qwen2.5-3B-512k-lc-39iters/vocab.json +0 -0
- Qwen2.5-3B-512k-mi-flexpf_090-39iters-2025041801/config.json +33 -0
- Qwen2.5-3B-512k-mi-flexpf_090-39iters-2025041801/generation_config.json +7 -0
- Qwen2.5-3B-512k-mi-flexpf_090-39iters-2025041801/modeling_qwen2.py +1136 -0
- Qwen2.5-3B-512k-mi-flexpf_090-39iters-2025041801/pytorch_model.bin +3 -0
- Qwen2.5-3B-512k-mi-flexpf_090-39iters-2025041801/tokenizer.json +0 -0
- Qwen2.5-3B-512k-mi-flexpf_090-39iters-2025041801/tokenizer_config.json +207 -0
- Qwen2.5-3B-512k-mi-flexpf_090-39iters-2025041801/vocab.json +0 -0
Qwen2.5-3B-512k-lc-39iters/.ipynb_checkpoints/config-checkpoint.json
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"Qwen2ForCausalLM"
|
4 |
+
],
|
5 |
+
"attention_dropout": 0.0,
|
6 |
+
"bos_token_id": 151643,
|
7 |
+
"eos_token_id": 151643,
|
8 |
+
"hidden_act": "silu",
|
9 |
+
"hidden_size": 2048,
|
10 |
+
"initializer_range": 0.02,
|
11 |
+
"intermediate_size": 11008,
|
12 |
+
"max_position_embeddings": 32768,
|
13 |
+
"max_window_layers": 36,
|
14 |
+
"model_type": "qwen2",
|
15 |
+
"num_attention_heads": 16,
|
16 |
+
"num_hidden_layers": 36,
|
17 |
+
"num_key_value_heads": 2,
|
18 |
+
"rms_norm_eps": 1e-06,
|
19 |
+
"rope_theta": 1000000.0,
|
20 |
+
"sliding_window": 32768,
|
21 |
+
"tie_word_embeddings": true,
|
22 |
+
"torch_dtype": "bfloat16",
|
23 |
+
"transformers_version": "4.40.1",
|
24 |
+
"use_cache": true,
|
25 |
+
"use_mrope": false,
|
26 |
+
"use_sliding_window": false,
|
27 |
+
"vocab_size": 151936
|
28 |
+
}
|
Qwen2.5-3B-512k-lc-39iters/config.json
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"Qwen2ForCausalLM"
|
4 |
+
],
|
5 |
+
"attention_dropout": 0.0,
|
6 |
+
"bos_token_id": 151643,
|
7 |
+
"eos_token_id": 151643,
|
8 |
+
"hidden_act": "silu",
|
9 |
+
"hidden_size": 2048,
|
10 |
+
"initializer_range": 0.02,
|
11 |
+
"intermediate_size": 11008,
|
12 |
+
"max_position_embeddings": 524288,
|
13 |
+
"rope_scaling": {
|
14 |
+
"factor": 16.0,
|
15 |
+
"original_max_position_embeddings": 32768,
|
16 |
+
"type": "yarn"
|
17 |
+
},
|
18 |
+
"max_window_layers": 36,
|
19 |
+
"model_type": "qwen2",
|
20 |
+
"num_attention_heads": 16,
|
21 |
+
"num_hidden_layers": 36,
|
22 |
+
"num_key_value_heads": 2,
|
23 |
+
"rms_norm_eps": 1e-06,
|
24 |
+
"rope_theta": 1000000.0,
|
25 |
+
"sliding_window": 32768,
|
26 |
+
"tie_word_embeddings": true,
|
27 |
+
"torch_dtype": "bfloat16",
|
28 |
+
"transformers_version": "4.40.1",
|
29 |
+
"use_cache": true,
|
30 |
+
"use_mrope": false,
|
31 |
+
"use_sliding_window": false,
|
32 |
+
"vocab_size": 151936
|
33 |
+
}
|
Qwen2.5-3B-512k-lc-39iters/generation_config.json
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token_id": 151643,
|
3 |
+
"do_sample": false,
|
4 |
+
"eos_token_id": 151643,
|
5 |
+
"max_new_tokens": 2048,
|
6 |
+
"transformers_version": "4.37.0"
|
7 |
+
}
|
Qwen2.5-3B-512k-lc-39iters/model-00001-of-00002.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6dc5a84b779e84f2ef9e3b08c537833d9caf2fa3ed4d980a882b9fd4a0a5c71d
|
3 |
+
size 4957560304
|
Qwen2.5-3B-512k-lc-39iters/model-00002-of-00002.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:68d0807cd96bc96d54d00bdb02561e5d7b82c7931a44cca30ae5250913171092
|
3 |
+
size 1214366696
|
Qwen2.5-3B-512k-lc-39iters/model.safetensors.index.json
ADDED
@@ -0,0 +1,441 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"metadata": {
|
3 |
+
"total_size": 6171877376
|
4 |
+
},
|
5 |
+
"weight_map": {
|
6 |
+
"model.embed_tokens.weight": "model-00001-of-00002.safetensors",
|
7 |
+
"model.layers.0.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
8 |
+
"model.layers.0.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
9 |
+
"model.layers.0.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
10 |
+
"model.layers.0.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
11 |
+
"model.layers.0.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
12 |
+
"model.layers.0.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
13 |
+
"model.layers.0.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
14 |
+
"model.layers.0.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
15 |
+
"model.layers.0.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
16 |
+
"model.layers.0.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
17 |
+
"model.layers.0.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
18 |
+
"model.layers.0.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
19 |
+
"model.layers.1.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
20 |
+
"model.layers.1.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
21 |
+
"model.layers.1.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
22 |
+
"model.layers.1.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
23 |
+
"model.layers.1.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
24 |
+
"model.layers.1.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
25 |
+
"model.layers.1.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
26 |
+
"model.layers.1.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
27 |
+
"model.layers.1.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
28 |
+
"model.layers.1.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
29 |
+
"model.layers.1.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
30 |
+
"model.layers.1.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
31 |
+
"model.layers.10.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
32 |
+
"model.layers.10.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
33 |
+
"model.layers.10.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
34 |
+
"model.layers.10.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
35 |
+
"model.layers.10.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
36 |
+
"model.layers.10.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
37 |
+
"model.layers.10.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
38 |
+
"model.layers.10.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
39 |
+
"model.layers.10.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
40 |
+
"model.layers.10.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
41 |
+
"model.layers.10.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
42 |
+
"model.layers.10.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
43 |
+
"model.layers.11.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
44 |
+
"model.layers.11.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
45 |
+
"model.layers.11.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
46 |
+
"model.layers.11.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
47 |
+
"model.layers.11.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
48 |
+
"model.layers.11.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
49 |
+
"model.layers.11.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
50 |
+
"model.layers.11.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
51 |
+
"model.layers.11.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
52 |
+
"model.layers.11.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
53 |
+
"model.layers.11.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
54 |
+
"model.layers.11.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
55 |
+
"model.layers.12.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
56 |
+
"model.layers.12.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
57 |
+
"model.layers.12.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
58 |
+
"model.layers.12.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
59 |
+
"model.layers.12.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
60 |
+
"model.layers.12.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
61 |
+
"model.layers.12.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
62 |
+
"model.layers.12.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
63 |
+
"model.layers.12.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
64 |
+
"model.layers.12.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
65 |
+
"model.layers.12.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
66 |
+
"model.layers.12.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
67 |
+
"model.layers.13.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
68 |
+
"model.layers.13.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
69 |
+
"model.layers.13.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
70 |
+
"model.layers.13.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
71 |
+
"model.layers.13.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
72 |
+
"model.layers.13.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
73 |
+
"model.layers.13.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
74 |
+
"model.layers.13.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
75 |
+
"model.layers.13.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
76 |
+
"model.layers.13.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
77 |
+
"model.layers.13.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
78 |
+
"model.layers.13.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
79 |
+
"model.layers.14.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
80 |
+
"model.layers.14.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
81 |
+
"model.layers.14.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
82 |
+
"model.layers.14.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
83 |
+
"model.layers.14.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
84 |
+
"model.layers.14.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
85 |
+
"model.layers.14.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
86 |
+
"model.layers.14.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
87 |
+
"model.layers.14.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
88 |
+
"model.layers.14.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
89 |
+
"model.layers.14.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
90 |
+
"model.layers.14.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
91 |
+
"model.layers.15.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
92 |
+
"model.layers.15.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
93 |
+
"model.layers.15.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
94 |
+
"model.layers.15.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
95 |
+
"model.layers.15.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
96 |
+
"model.layers.15.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
97 |
+
"model.layers.15.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
98 |
+
"model.layers.15.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
99 |
+
"model.layers.15.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
100 |
+
"model.layers.15.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
101 |
+
"model.layers.15.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
102 |
+
"model.layers.15.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
103 |
+
"model.layers.16.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
104 |
+
"model.layers.16.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
105 |
+
"model.layers.16.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
106 |
+
"model.layers.16.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
107 |
+
"model.layers.16.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
108 |
+
"model.layers.16.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
109 |
+
"model.layers.16.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
110 |
+
"model.layers.16.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
111 |
+
"model.layers.16.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
112 |
+
"model.layers.16.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
113 |
+
"model.layers.16.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
114 |
+
"model.layers.16.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
115 |
+
"model.layers.17.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
116 |
+
"model.layers.17.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
117 |
+
"model.layers.17.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
118 |
+
"model.layers.17.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
119 |
+
"model.layers.17.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
120 |
+
"model.layers.17.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
121 |
+
"model.layers.17.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
122 |
+
"model.layers.17.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
123 |
+
"model.layers.17.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
124 |
+
"model.layers.17.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
125 |
+
"model.layers.17.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
126 |
+
"model.layers.17.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
127 |
+
"model.layers.18.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
128 |
+
"model.layers.18.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
129 |
+
"model.layers.18.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
130 |
+
"model.layers.18.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
131 |
+
"model.layers.18.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
132 |
+
"model.layers.18.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
133 |
+
"model.layers.18.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
134 |
+
"model.layers.18.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
135 |
+
"model.layers.18.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
136 |
+
"model.layers.18.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
137 |
+
"model.layers.18.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
138 |
+
"model.layers.18.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
139 |
+
"model.layers.19.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
140 |
+
"model.layers.19.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
141 |
+
"model.layers.19.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
142 |
+
"model.layers.19.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
143 |
+
"model.layers.19.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
144 |
+
"model.layers.19.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
145 |
+
"model.layers.19.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
146 |
+
"model.layers.19.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
147 |
+
"model.layers.19.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
148 |
+
"model.layers.19.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
149 |
+
"model.layers.19.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
150 |
+
"model.layers.19.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
151 |
+
"model.layers.2.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
152 |
+
"model.layers.2.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
153 |
+
"model.layers.2.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
154 |
+
"model.layers.2.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
155 |
+
"model.layers.2.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
156 |
+
"model.layers.2.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
157 |
+
"model.layers.2.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
158 |
+
"model.layers.2.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
159 |
+
"model.layers.2.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
160 |
+
"model.layers.2.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
161 |
+
"model.layers.2.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
162 |
+
"model.layers.2.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
163 |
+
"model.layers.20.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
164 |
+
"model.layers.20.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
165 |
+
"model.layers.20.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
166 |
+
"model.layers.20.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
167 |
+
"model.layers.20.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
168 |
+
"model.layers.20.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
169 |
+
"model.layers.20.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
170 |
+
"model.layers.20.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
171 |
+
"model.layers.20.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
172 |
+
"model.layers.20.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
173 |
+
"model.layers.20.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
174 |
+
"model.layers.20.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
175 |
+
"model.layers.21.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
176 |
+
"model.layers.21.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
177 |
+
"model.layers.21.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
178 |
+
"model.layers.21.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
179 |
+
"model.layers.21.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
180 |
+
"model.layers.21.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
181 |
+
"model.layers.21.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
182 |
+
"model.layers.21.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
183 |
+
"model.layers.21.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
184 |
+
"model.layers.21.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
185 |
+
"model.layers.21.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
186 |
+
"model.layers.21.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
187 |
+
"model.layers.22.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
188 |
+
"model.layers.22.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
189 |
+
"model.layers.22.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
190 |
+
"model.layers.22.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
191 |
+
"model.layers.22.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
192 |
+
"model.layers.22.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
193 |
+
"model.layers.22.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
194 |
+
"model.layers.22.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
195 |
+
"model.layers.22.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
196 |
+
"model.layers.22.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
197 |
+
"model.layers.22.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
198 |
+
"model.layers.22.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
199 |
+
"model.layers.23.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
200 |
+
"model.layers.23.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
201 |
+
"model.layers.23.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
202 |
+
"model.layers.23.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
203 |
+
"model.layers.23.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
204 |
+
"model.layers.23.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
205 |
+
"model.layers.23.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
206 |
+
"model.layers.23.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
207 |
+
"model.layers.23.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
208 |
+
"model.layers.23.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
209 |
+
"model.layers.23.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
210 |
+
"model.layers.23.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
211 |
+
"model.layers.24.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
212 |
+
"model.layers.24.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
213 |
+
"model.layers.24.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
214 |
+
"model.layers.24.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
215 |
+
"model.layers.24.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
216 |
+
"model.layers.24.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
217 |
+
"model.layers.24.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
218 |
+
"model.layers.24.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
219 |
+
"model.layers.24.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
220 |
+
"model.layers.24.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
221 |
+
"model.layers.24.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
222 |
+
"model.layers.24.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
223 |
+
"model.layers.25.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
224 |
+
"model.layers.25.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
225 |
+
"model.layers.25.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
226 |
+
"model.layers.25.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
227 |
+
"model.layers.25.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
228 |
+
"model.layers.25.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
229 |
+
"model.layers.25.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
230 |
+
"model.layers.25.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
231 |
+
"model.layers.25.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
232 |
+
"model.layers.25.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
233 |
+
"model.layers.25.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
234 |
+
"model.layers.25.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
235 |
+
"model.layers.26.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
236 |
+
"model.layers.26.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
237 |
+
"model.layers.26.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
238 |
+
"model.layers.26.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
239 |
+
"model.layers.26.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
240 |
+
"model.layers.26.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
241 |
+
"model.layers.26.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
242 |
+
"model.layers.26.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
243 |
+
"model.layers.26.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
244 |
+
"model.layers.26.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
245 |
+
"model.layers.26.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
246 |
+
"model.layers.26.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
247 |
+
"model.layers.27.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
248 |
+
"model.layers.27.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
249 |
+
"model.layers.27.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
250 |
+
"model.layers.27.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
251 |
+
"model.layers.27.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
252 |
+
"model.layers.27.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
253 |
+
"model.layers.27.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
254 |
+
"model.layers.27.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
255 |
+
"model.layers.27.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
256 |
+
"model.layers.27.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
257 |
+
"model.layers.27.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
258 |
+
"model.layers.27.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
259 |
+
"model.layers.28.input_layernorm.weight": "model-00002-of-00002.safetensors",
|
260 |
+
"model.layers.28.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
|
261 |
+
"model.layers.28.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
|
262 |
+
"model.layers.28.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
|
263 |
+
"model.layers.28.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
|
264 |
+
"model.layers.28.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
265 |
+
"model.layers.28.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
266 |
+
"model.layers.28.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
267 |
+
"model.layers.28.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
268 |
+
"model.layers.28.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
269 |
+
"model.layers.28.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
270 |
+
"model.layers.28.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
271 |
+
"model.layers.29.input_layernorm.weight": "model-00002-of-00002.safetensors",
|
272 |
+
"model.layers.29.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
|
273 |
+
"model.layers.29.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
|
274 |
+
"model.layers.29.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
|
275 |
+
"model.layers.29.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
|
276 |
+
"model.layers.29.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
|
277 |
+
"model.layers.29.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
|
278 |
+
"model.layers.29.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
|
279 |
+
"model.layers.29.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
|
280 |
+
"model.layers.29.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
|
281 |
+
"model.layers.29.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
|
282 |
+
"model.layers.29.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
|
283 |
+
"model.layers.3.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
284 |
+
"model.layers.3.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
285 |
+
"model.layers.3.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
286 |
+
"model.layers.3.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
287 |
+
"model.layers.3.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
288 |
+
"model.layers.3.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
289 |
+
"model.layers.3.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
290 |
+
"model.layers.3.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
291 |
+
"model.layers.3.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
292 |
+
"model.layers.3.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
293 |
+
"model.layers.3.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
294 |
+
"model.layers.3.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
295 |
+
"model.layers.30.input_layernorm.weight": "model-00002-of-00002.safetensors",
|
296 |
+
"model.layers.30.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
|
297 |
+
"model.layers.30.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
|
298 |
+
"model.layers.30.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
|
299 |
+
"model.layers.30.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
|
300 |
+
"model.layers.30.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
|
301 |
+
"model.layers.30.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
|
302 |
+
"model.layers.30.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
|
303 |
+
"model.layers.30.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
|
304 |
+
"model.layers.30.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
|
305 |
+
"model.layers.30.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
|
306 |
+
"model.layers.30.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
|
307 |
+
"model.layers.31.input_layernorm.weight": "model-00002-of-00002.safetensors",
|
308 |
+
"model.layers.31.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
|
309 |
+
"model.layers.31.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
|
310 |
+
"model.layers.31.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
|
311 |
+
"model.layers.31.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
|
312 |
+
"model.layers.31.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
|
313 |
+
"model.layers.31.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
|
314 |
+
"model.layers.31.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
|
315 |
+
"model.layers.31.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
|
316 |
+
"model.layers.31.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
|
317 |
+
"model.layers.31.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
|
318 |
+
"model.layers.31.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
|
319 |
+
"model.layers.32.input_layernorm.weight": "model-00002-of-00002.safetensors",
|
320 |
+
"model.layers.32.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
|
321 |
+
"model.layers.32.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
|
322 |
+
"model.layers.32.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
|
323 |
+
"model.layers.32.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
|
324 |
+
"model.layers.32.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
|
325 |
+
"model.layers.32.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
|
326 |
+
"model.layers.32.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
|
327 |
+
"model.layers.32.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
|
328 |
+
"model.layers.32.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
|
329 |
+
"model.layers.32.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
|
330 |
+
"model.layers.32.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
|
331 |
+
"model.layers.33.input_layernorm.weight": "model-00002-of-00002.safetensors",
|
332 |
+
"model.layers.33.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
|
333 |
+
"model.layers.33.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
|
334 |
+
"model.layers.33.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
|
335 |
+
"model.layers.33.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
|
336 |
+
"model.layers.33.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
|
337 |
+
"model.layers.33.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
|
338 |
+
"model.layers.33.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
|
339 |
+
"model.layers.33.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
|
340 |
+
"model.layers.33.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
|
341 |
+
"model.layers.33.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
|
342 |
+
"model.layers.33.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
|
343 |
+
"model.layers.34.input_layernorm.weight": "model-00002-of-00002.safetensors",
|
344 |
+
"model.layers.34.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
|
345 |
+
"model.layers.34.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
|
346 |
+
"model.layers.34.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
|
347 |
+
"model.layers.34.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
|
348 |
+
"model.layers.34.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
|
349 |
+
"model.layers.34.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
|
350 |
+
"model.layers.34.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
|
351 |
+
"model.layers.34.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
|
352 |
+
"model.layers.34.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
|
353 |
+
"model.layers.34.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
|
354 |
+
"model.layers.34.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
|
355 |
+
"model.layers.35.input_layernorm.weight": "model-00002-of-00002.safetensors",
|
356 |
+
"model.layers.35.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
|
357 |
+
"model.layers.35.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
|
358 |
+
"model.layers.35.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
|
359 |
+
"model.layers.35.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
|
360 |
+
"model.layers.35.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
|
361 |
+
"model.layers.35.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
|
362 |
+
"model.layers.35.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
|
363 |
+
"model.layers.35.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
|
364 |
+
"model.layers.35.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
|
365 |
+
"model.layers.35.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
|
366 |
+
"model.layers.35.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
|
367 |
+
"model.layers.4.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
368 |
+
"model.layers.4.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
369 |
+
"model.layers.4.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
370 |
+
"model.layers.4.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
371 |
+
"model.layers.4.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
372 |
+
"model.layers.4.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
373 |
+
"model.layers.4.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
374 |
+
"model.layers.4.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
375 |
+
"model.layers.4.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
376 |
+
"model.layers.4.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
377 |
+
"model.layers.4.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
378 |
+
"model.layers.4.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
379 |
+
"model.layers.5.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
380 |
+
"model.layers.5.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
381 |
+
"model.layers.5.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
382 |
+
"model.layers.5.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
383 |
+
"model.layers.5.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
384 |
+
"model.layers.5.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
385 |
+
"model.layers.5.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
386 |
+
"model.layers.5.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
387 |
+
"model.layers.5.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
388 |
+
"model.layers.5.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
389 |
+
"model.layers.5.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
390 |
+
"model.layers.5.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
391 |
+
"model.layers.6.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
392 |
+
"model.layers.6.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
393 |
+
"model.layers.6.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
394 |
+
"model.layers.6.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
395 |
+
"model.layers.6.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
396 |
+
"model.layers.6.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
397 |
+
"model.layers.6.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
398 |
+
"model.layers.6.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
399 |
+
"model.layers.6.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
400 |
+
"model.layers.6.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
401 |
+
"model.layers.6.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
402 |
+
"model.layers.6.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
403 |
+
"model.layers.7.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
404 |
+
"model.layers.7.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
405 |
+
"model.layers.7.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
406 |
+
"model.layers.7.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
407 |
+
"model.layers.7.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
408 |
+
"model.layers.7.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
409 |
+
"model.layers.7.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
410 |
+
"model.layers.7.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
411 |
+
"model.layers.7.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
412 |
+
"model.layers.7.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
413 |
+
"model.layers.7.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
414 |
+
"model.layers.7.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
415 |
+
"model.layers.8.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
416 |
+
"model.layers.8.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
417 |
+
"model.layers.8.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
418 |
+
"model.layers.8.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
419 |
+
"model.layers.8.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
420 |
+
"model.layers.8.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
421 |
+
"model.layers.8.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
422 |
+
"model.layers.8.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
423 |
+
"model.layers.8.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
424 |
+
"model.layers.8.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
425 |
+
"model.layers.8.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
426 |
+
"model.layers.8.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
427 |
+
"model.layers.9.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
428 |
+
"model.layers.9.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
|
429 |
+
"model.layers.9.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
|
430 |
+
"model.layers.9.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
|
431 |
+
"model.layers.9.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
|
432 |
+
"model.layers.9.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
433 |
+
"model.layers.9.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
434 |
+
"model.layers.9.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
|
435 |
+
"model.layers.9.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
436 |
+
"model.layers.9.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
437 |
+
"model.layers.9.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
438 |
+
"model.layers.9.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
439 |
+
"model.norm.weight": "model-00002-of-00002.safetensors"
|
440 |
+
}
|
441 |
+
}
|
Qwen2.5-3B-512k-lc-39iters/modeling_qwen2.py
ADDED
@@ -0,0 +1,1136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
2 |
+
# This file was automatically generated from src/transformers/models/qwen2/modular_qwen2.py.
|
3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
5 |
+
# modular_qwen2.py file directly. One of our CI enforces this.
|
6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
7 |
+
from typing import Callable, List, Optional, Tuple, Union
|
8 |
+
|
9 |
+
import torch
|
10 |
+
from torch import nn
|
11 |
+
|
12 |
+
from transformers.activations import ACT2FN
|
13 |
+
from transformers.cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCache
|
14 |
+
from transformers.generation import GenerationMixin
|
15 |
+
from transformers.modeling_attn_mask_utils import AttentionMaskConverter
|
16 |
+
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
|
17 |
+
from transformers.modeling_outputs import (
|
18 |
+
BaseModelOutputWithPast,
|
19 |
+
CausalLMOutputWithPast,
|
20 |
+
SequenceClassifierOutputWithPast,
|
21 |
+
QuestionAnsweringModelOutput,
|
22 |
+
TokenClassifierOutput,
|
23 |
+
)
|
24 |
+
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
|
25 |
+
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
26 |
+
from transformers.processing_utils import Unpack
|
27 |
+
from transformers.utils import (
|
28 |
+
LossKwargs,
|
29 |
+
add_code_sample_docstrings,
|
30 |
+
add_start_docstrings,
|
31 |
+
add_start_docstrings_to_model_forward,
|
32 |
+
logging,
|
33 |
+
replace_return_docstrings,
|
34 |
+
)
|
35 |
+
from transformers.utils.deprecation import deprecate_kwarg
|
36 |
+
from .configuration_qwen2 import Qwen2Config
|
37 |
+
|
38 |
+
|
39 |
+
logger = logging.get_logger(__name__)
|
40 |
+
|
41 |
+
_CHECKPOINT_FOR_DOC = "meta-qwen2/Qwen2-2-7b-hf"
|
42 |
+
_CONFIG_FOR_DOC = "Qwen2Config"
|
43 |
+
|
44 |
+
QWEN_ATTN_FUNCS = ALL_ATTENTION_FUNCTIONS.copy()
|
45 |
+
|
46 |
+
class Qwen2MLP(nn.Module):
|
47 |
+
def __init__(self, config):
|
48 |
+
super().__init__()
|
49 |
+
self.config = config
|
50 |
+
self.hidden_size = config.hidden_size
|
51 |
+
self.intermediate_size = config.intermediate_size
|
52 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
53 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
54 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
55 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
56 |
+
|
57 |
+
def forward(self, x):
|
58 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
59 |
+
return down_proj
|
60 |
+
|
61 |
+
|
62 |
+
def rotate_half(x):
|
63 |
+
"""Rotates half the hidden dims of the input."""
|
64 |
+
x1 = x[..., : x.shape[-1] // 2]
|
65 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
66 |
+
return torch.cat((-x2, x1), dim=-1)
|
67 |
+
|
68 |
+
|
69 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
70 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
71 |
+
|
72 |
+
Args:
|
73 |
+
q (`torch.Tensor`): The query tensor.
|
74 |
+
k (`torch.Tensor`): The key tensor.
|
75 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
76 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
77 |
+
position_ids (`torch.Tensor`, *optional*):
|
78 |
+
Deprecated and unused.
|
79 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
80 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
81 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
82 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
83 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
84 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
85 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
86 |
+
Returns:
|
87 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
88 |
+
"""
|
89 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
90 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
91 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
92 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
93 |
+
return q_embed, k_embed
|
94 |
+
|
95 |
+
|
96 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
97 |
+
"""
|
98 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
99 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
100 |
+
"""
|
101 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
102 |
+
if n_rep == 1:
|
103 |
+
return hidden_states
|
104 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
105 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
106 |
+
|
107 |
+
|
108 |
+
def eager_attention_forward(
|
109 |
+
module: nn.Module,
|
110 |
+
query: torch.Tensor,
|
111 |
+
key: torch.Tensor,
|
112 |
+
value: torch.Tensor,
|
113 |
+
attention_mask: Optional[torch.Tensor],
|
114 |
+
scaling: float,
|
115 |
+
dropout: float = 0.0,
|
116 |
+
**kwargs,
|
117 |
+
):
|
118 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
119 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
120 |
+
|
121 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
122 |
+
if attention_mask is not None:
|
123 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
124 |
+
attn_weights = attn_weights + causal_mask
|
125 |
+
|
126 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
127 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
128 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
129 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
130 |
+
|
131 |
+
return attn_output, attn_weights
|
132 |
+
|
133 |
+
|
134 |
+
class Qwen2Attention(nn.Module):
|
135 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
136 |
+
|
137 |
+
def __init__(self, config: Qwen2Config, layer_idx: int):
|
138 |
+
super().__init__()
|
139 |
+
self.config = config
|
140 |
+
self.layer_idx = layer_idx
|
141 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
142 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
143 |
+
self.scaling = self.head_dim**-0.5
|
144 |
+
self.attention_dropout = config.attention_dropout
|
145 |
+
self.is_causal = True
|
146 |
+
self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=True)
|
147 |
+
self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
|
148 |
+
self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
|
149 |
+
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
|
150 |
+
|
151 |
+
def forward(
|
152 |
+
self,
|
153 |
+
hidden_states: torch.Tensor,
|
154 |
+
position_embeddings: Tuple[torch.Tensor, torch.Tensor],
|
155 |
+
attention_mask: Optional[torch.Tensor],
|
156 |
+
past_key_value: Optional[Cache] = None,
|
157 |
+
cache_position: Optional[torch.LongTensor] = None,
|
158 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
159 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
160 |
+
input_shape = hidden_states.shape[:-1]
|
161 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
162 |
+
|
163 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
164 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
165 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
166 |
+
|
167 |
+
cos, sin = position_embeddings
|
168 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
169 |
+
|
170 |
+
if past_key_value is not None:
|
171 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
172 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
173 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
174 |
+
|
175 |
+
sliding_window = None
|
176 |
+
if (
|
177 |
+
self.config.use_sliding_window
|
178 |
+
and getattr(self.config, "sliding_window", None) is not None
|
179 |
+
and self.layer_idx >= self.config.max_window_layers
|
180 |
+
):
|
181 |
+
sliding_window = self.config.sliding_window
|
182 |
+
|
183 |
+
attention_interface: Callable = eager_attention_forward
|
184 |
+
if self.config._attn_implementation != "eager":
|
185 |
+
if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
|
186 |
+
logger.warning_once(
|
187 |
+
"`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
|
188 |
+
'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
189 |
+
)
|
190 |
+
else:
|
191 |
+
attention_interface = QWEN_ATTN_FUNCS[self.config._attn_implementation]
|
192 |
+
|
193 |
+
attn_output, attn_weights = attention_interface(
|
194 |
+
self,
|
195 |
+
query_states,
|
196 |
+
key_states,
|
197 |
+
value_states,
|
198 |
+
attention_mask,
|
199 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
200 |
+
scaling=self.scaling,
|
201 |
+
sliding_window=sliding_window, # main diff with Llama
|
202 |
+
**kwargs,
|
203 |
+
)
|
204 |
+
|
205 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
206 |
+
attn_output = self.o_proj(attn_output)
|
207 |
+
return attn_output, attn_weights
|
208 |
+
|
209 |
+
|
210 |
+
class Qwen2RMSNorm(nn.Module):
|
211 |
+
def __init__(self, hidden_size, eps=1e-6):
|
212 |
+
"""
|
213 |
+
Qwen2RMSNorm is equivalent to T5LayerNorm
|
214 |
+
"""
|
215 |
+
super().__init__()
|
216 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
217 |
+
self.variance_epsilon = eps
|
218 |
+
|
219 |
+
def forward(self, hidden_states):
|
220 |
+
input_dtype = hidden_states.dtype
|
221 |
+
hidden_states = hidden_states.to(torch.float32)
|
222 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
223 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
224 |
+
return self.weight * hidden_states.to(input_dtype)
|
225 |
+
|
226 |
+
def extra_repr(self):
|
227 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
228 |
+
|
229 |
+
|
230 |
+
class Qwen2DecoderLayer(nn.Module):
|
231 |
+
def __init__(self, config: Qwen2Config, layer_idx: int):
|
232 |
+
super().__init__()
|
233 |
+
self.hidden_size = config.hidden_size
|
234 |
+
self.self_attn = Qwen2Attention(config=config, layer_idx=layer_idx)
|
235 |
+
self.mlp = Qwen2MLP(config)
|
236 |
+
self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
237 |
+
self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
238 |
+
if config.sliding_window and config._attn_implementation != "flash_attention_2":
|
239 |
+
logger.warning_once(
|
240 |
+
f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
|
241 |
+
"unexpected results may be encountered."
|
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: Optional[bool] = False,
|
251 |
+
use_cache: Optional[bool] = False,
|
252 |
+
cache_position: Optional[torch.LongTensor] = None,
|
253 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
|
254 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
255 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
256 |
+
residual = hidden_states
|
257 |
+
|
258 |
+
hidden_states = self.input_layernorm(hidden_states)
|
259 |
+
|
260 |
+
# Self Attention
|
261 |
+
hidden_states, self_attn_weights = self.self_attn(
|
262 |
+
hidden_states=hidden_states,
|
263 |
+
attention_mask=attention_mask,
|
264 |
+
position_ids=position_ids,
|
265 |
+
past_key_value=past_key_value,
|
266 |
+
output_attentions=output_attentions,
|
267 |
+
use_cache=use_cache,
|
268 |
+
cache_position=cache_position,
|
269 |
+
position_embeddings=position_embeddings,
|
270 |
+
**kwargs,
|
271 |
+
)
|
272 |
+
hidden_states = residual + hidden_states
|
273 |
+
|
274 |
+
# Fully Connected
|
275 |
+
residual = hidden_states
|
276 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
277 |
+
hidden_states = self.mlp(hidden_states)
|
278 |
+
hidden_states = residual + hidden_states
|
279 |
+
|
280 |
+
outputs = (hidden_states,)
|
281 |
+
if output_attentions:
|
282 |
+
outputs += (self_attn_weights,)
|
283 |
+
|
284 |
+
return outputs
|
285 |
+
|
286 |
+
|
287 |
+
class Qwen2RotaryEmbedding(nn.Module):
|
288 |
+
def __init__(self, config: Qwen2Config, device=None):
|
289 |
+
super().__init__()
|
290 |
+
# BC: "rope_type" was originally "type"
|
291 |
+
if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
|
292 |
+
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
293 |
+
else:
|
294 |
+
self.rope_type = "default"
|
295 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
296 |
+
self.original_max_seq_len = config.max_position_embeddings
|
297 |
+
|
298 |
+
self.config = config
|
299 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
300 |
+
|
301 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
|
302 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
303 |
+
self.original_inv_freq = self.inv_freq
|
304 |
+
|
305 |
+
def _dynamic_frequency_update(self, position_ids, device):
|
306 |
+
"""
|
307 |
+
dynamic RoPE layers should recompute `inv_freq` in the following situations:
|
308 |
+
1 - growing beyond the cached sequence length (allow scaling)
|
309 |
+
2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
|
310 |
+
"""
|
311 |
+
seq_len = torch.max(position_ids) + 1
|
312 |
+
if seq_len > self.max_seq_len_cached: # growth
|
313 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
|
314 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
|
315 |
+
self.max_seq_len_cached = seq_len
|
316 |
+
|
317 |
+
if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
|
318 |
+
# This .to() is needed if the model has been moved to a device after being initialized (because
|
319 |
+
# the buffer is automatically moved, but not the original copy)
|
320 |
+
self.original_inv_freq = self.original_inv_freq.to(device)
|
321 |
+
self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
|
322 |
+
self.max_seq_len_cached = self.original_max_seq_len
|
323 |
+
|
324 |
+
@torch.no_grad()
|
325 |
+
def forward(self, x, position_ids):
|
326 |
+
if "dynamic" in self.rope_type:
|
327 |
+
self._dynamic_frequency_update(position_ids, device=x.device)
|
328 |
+
|
329 |
+
# Core RoPE block
|
330 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
331 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
332 |
+
# Force float32 (see https://github.com/huggingface/transformers/pull/29285)
|
333 |
+
device_type = x.device.type
|
334 |
+
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
|
335 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
336 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
337 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
338 |
+
cos = emb.cos()
|
339 |
+
sin = emb.sin()
|
340 |
+
|
341 |
+
# Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
|
342 |
+
cos = cos * self.attention_scaling
|
343 |
+
sin = sin * self.attention_scaling
|
344 |
+
|
345 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
346 |
+
|
347 |
+
|
348 |
+
QWEN2_START_DOCSTRING = r"""
|
349 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
350 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
351 |
+
etc.)
|
352 |
+
|
353 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
354 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
355 |
+
and behavior.
|
356 |
+
|
357 |
+
Parameters:
|
358 |
+
config ([`Qwen2Config`]):
|
359 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
360 |
+
load the weights associated with the model, only the configuration. Check out the
|
361 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
362 |
+
"""
|
363 |
+
|
364 |
+
|
365 |
+
@add_start_docstrings(
|
366 |
+
"The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
|
367 |
+
QWEN2_START_DOCSTRING,
|
368 |
+
)
|
369 |
+
class Qwen2PreTrainedModel(PreTrainedModel):
|
370 |
+
config_class = Qwen2Config
|
371 |
+
base_model_prefix = "model"
|
372 |
+
supports_gradient_checkpointing = True
|
373 |
+
_no_split_modules = ["Qwen2DecoderLayer"]
|
374 |
+
_skip_keys_device_placement = ["past_key_values"]
|
375 |
+
_supports_flash_attn_2 = True
|
376 |
+
_supports_sdpa = True
|
377 |
+
_supports_flex_attn = True
|
378 |
+
_supports_cache_class = True
|
379 |
+
_supports_quantized_cache = True
|
380 |
+
_supports_static_cache = True
|
381 |
+
_supports_attention_backend = True
|
382 |
+
|
383 |
+
def _init_weights(self, module):
|
384 |
+
std = self.config.initializer_range
|
385 |
+
if isinstance(module, nn.Linear):
|
386 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
387 |
+
if module.bias is not None:
|
388 |
+
module.bias.data.zero_()
|
389 |
+
elif isinstance(module, nn.Embedding):
|
390 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
391 |
+
if module.padding_idx is not None:
|
392 |
+
module.weight.data[module.padding_idx].zero_()
|
393 |
+
|
394 |
+
|
395 |
+
QWEN2_INPUTS_DOCSTRING = r"""
|
396 |
+
Args:
|
397 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
398 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
399 |
+
it.
|
400 |
+
|
401 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
402 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
403 |
+
|
404 |
+
[What are input IDs?](../glossary#input-ids)
|
405 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
406 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
407 |
+
|
408 |
+
- 1 for tokens that are **not masked**,
|
409 |
+
- 0 for tokens that are **masked**.
|
410 |
+
|
411 |
+
[What are attention masks?](../glossary#attention-mask)
|
412 |
+
|
413 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
414 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
415 |
+
|
416 |
+
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
|
417 |
+
`past_key_values`).
|
418 |
+
|
419 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
420 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
421 |
+
information on the default strategy.
|
422 |
+
|
423 |
+
- 1 indicates the head is **not masked**,
|
424 |
+
- 0 indicates the head is **masked**.
|
425 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
426 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
427 |
+
config.n_positions - 1]`.
|
428 |
+
|
429 |
+
[What are position IDs?](../glossary#position-ids)
|
430 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
431 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
432 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
433 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
434 |
+
|
435 |
+
Two formats are allowed:
|
436 |
+
- a [`~cache_utils.Cache`] instance, see our
|
437 |
+
[kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
|
438 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
439 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
440 |
+
cache format.
|
441 |
+
|
442 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
443 |
+
legacy cache format will be returned.
|
444 |
+
|
445 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
446 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
447 |
+
of shape `(batch_size, sequence_length)`.
|
448 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
449 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
450 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
451 |
+
model's internal embedding lookup matrix.
|
452 |
+
use_cache (`bool`, *optional*):
|
453 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
454 |
+
`past_key_values`).
|
455 |
+
output_attentions (`bool`, *optional*):
|
456 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
457 |
+
tensors for more detail.
|
458 |
+
output_hidden_states (`bool`, *optional*):
|
459 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
460 |
+
more detail.
|
461 |
+
return_dict (`bool`, *optional*):
|
462 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
463 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
464 |
+
Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
|
465 |
+
this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
|
466 |
+
the complete sequence length.
|
467 |
+
"""
|
468 |
+
|
469 |
+
|
470 |
+
@add_start_docstrings(
|
471 |
+
"The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
|
472 |
+
QWEN2_START_DOCSTRING,
|
473 |
+
)
|
474 |
+
class Qwen2Model(Qwen2PreTrainedModel):
|
475 |
+
"""
|
476 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
|
477 |
+
|
478 |
+
Args:
|
479 |
+
config: Qwen2Config
|
480 |
+
"""
|
481 |
+
|
482 |
+
def __init__(self, config: Qwen2Config):
|
483 |
+
super().__init__(config)
|
484 |
+
self.padding_idx = config.pad_token_id
|
485 |
+
self.vocab_size = config.vocab_size
|
486 |
+
|
487 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
488 |
+
self.layers = nn.ModuleList(
|
489 |
+
[Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
490 |
+
)
|
491 |
+
self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
492 |
+
self.rotary_emb = Qwen2RotaryEmbedding(config=config)
|
493 |
+
self.gradient_checkpointing = False
|
494 |
+
|
495 |
+
# Initialize weights and apply final processing
|
496 |
+
self.post_init()
|
497 |
+
|
498 |
+
def get_input_embeddings(self):
|
499 |
+
return self.embed_tokens
|
500 |
+
|
501 |
+
def set_input_embeddings(self, value):
|
502 |
+
self.embed_tokens = value
|
503 |
+
|
504 |
+
@add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
|
505 |
+
def forward(
|
506 |
+
self,
|
507 |
+
input_ids: torch.LongTensor = None,
|
508 |
+
attention_mask: Optional[torch.Tensor] = None,
|
509 |
+
position_ids: Optional[torch.LongTensor] = None,
|
510 |
+
past_key_values: Optional[Cache] = None,
|
511 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
512 |
+
use_cache: Optional[bool] = None,
|
513 |
+
output_attentions: Optional[bool] = None,
|
514 |
+
output_hidden_states: Optional[bool] = None,
|
515 |
+
return_dict: Optional[bool] = None,
|
516 |
+
cache_position: Optional[torch.LongTensor] = None,
|
517 |
+
**flash_attn_kwargs: Unpack[FlashAttentionKwargs],
|
518 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
519 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
520 |
+
output_hidden_states = (
|
521 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
522 |
+
)
|
523 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
524 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
525 |
+
|
526 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
527 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
528 |
+
|
529 |
+
if self.gradient_checkpointing and self.training and use_cache:
|
530 |
+
logger.warning_once(
|
531 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
|
532 |
+
)
|
533 |
+
use_cache = False
|
534 |
+
|
535 |
+
if inputs_embeds is None:
|
536 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
537 |
+
|
538 |
+
if use_cache and past_key_values is None:
|
539 |
+
past_key_values = DynamicCache()
|
540 |
+
|
541 |
+
if cache_position is None:
|
542 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
543 |
+
cache_position = torch.arange(
|
544 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
545 |
+
)
|
546 |
+
|
547 |
+
if position_ids is None:
|
548 |
+
position_ids = cache_position.unsqueeze(0)
|
549 |
+
|
550 |
+
causal_mask = self._update_causal_mask(
|
551 |
+
attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
|
552 |
+
)
|
553 |
+
|
554 |
+
hidden_states = inputs_embeds
|
555 |
+
|
556 |
+
# create position embeddings to be shared across the decoder layers
|
557 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
558 |
+
|
559 |
+
# decoder layers
|
560 |
+
all_hidden_states = () if output_hidden_states else None
|
561 |
+
all_self_attns = () if output_attentions else None
|
562 |
+
|
563 |
+
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
|
564 |
+
if output_hidden_states:
|
565 |
+
all_hidden_states += (hidden_states,)
|
566 |
+
|
567 |
+
if self.gradient_checkpointing and self.training:
|
568 |
+
layer_outputs = self._gradient_checkpointing_func(
|
569 |
+
decoder_layer.__call__,
|
570 |
+
hidden_states,
|
571 |
+
causal_mask,
|
572 |
+
position_ids,
|
573 |
+
past_key_values,
|
574 |
+
output_attentions,
|
575 |
+
use_cache,
|
576 |
+
cache_position,
|
577 |
+
position_embeddings,
|
578 |
+
)
|
579 |
+
else:
|
580 |
+
layer_outputs = decoder_layer(
|
581 |
+
hidden_states,
|
582 |
+
attention_mask=causal_mask,
|
583 |
+
position_ids=position_ids,
|
584 |
+
past_key_value=past_key_values,
|
585 |
+
output_attentions=output_attentions,
|
586 |
+
use_cache=use_cache,
|
587 |
+
cache_position=cache_position,
|
588 |
+
position_embeddings=position_embeddings,
|
589 |
+
**flash_attn_kwargs,
|
590 |
+
)
|
591 |
+
|
592 |
+
hidden_states = layer_outputs[0]
|
593 |
+
|
594 |
+
if output_attentions:
|
595 |
+
all_self_attns += (layer_outputs[1],)
|
596 |
+
|
597 |
+
hidden_states = self.norm(hidden_states)
|
598 |
+
|
599 |
+
# add hidden states from the last decoder layer
|
600 |
+
if output_hidden_states:
|
601 |
+
all_hidden_states += (hidden_states,)
|
602 |
+
|
603 |
+
output = BaseModelOutputWithPast(
|
604 |
+
last_hidden_state=hidden_states,
|
605 |
+
past_key_values=past_key_values if use_cache else None,
|
606 |
+
hidden_states=all_hidden_states,
|
607 |
+
attentions=all_self_attns,
|
608 |
+
)
|
609 |
+
return output if return_dict else output.to_tuple()
|
610 |
+
|
611 |
+
def _update_causal_mask(
|
612 |
+
self,
|
613 |
+
attention_mask: torch.Tensor,
|
614 |
+
input_tensor: torch.Tensor,
|
615 |
+
cache_position: torch.Tensor,
|
616 |
+
past_key_values: Cache,
|
617 |
+
output_attentions: bool,
|
618 |
+
):
|
619 |
+
if self.config._attn_implementation == "flash_attention_2":
|
620 |
+
if attention_mask is not None and (attention_mask == 0.0).any():
|
621 |
+
return attention_mask
|
622 |
+
return None
|
623 |
+
|
624 |
+
# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
|
625 |
+
# order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
|
626 |
+
# to infer the attention mask.
|
627 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
628 |
+
using_static_cache = isinstance(past_key_values, StaticCache)
|
629 |
+
|
630 |
+
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
|
631 |
+
if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
|
632 |
+
if AttentionMaskConverter._ignore_causal_mask_sdpa(
|
633 |
+
attention_mask,
|
634 |
+
inputs_embeds=input_tensor,
|
635 |
+
past_key_values_length=past_seen_tokens,
|
636 |
+
is_training=self.training,
|
637 |
+
):
|
638 |
+
return None
|
639 |
+
|
640 |
+
dtype, device = input_tensor.dtype, input_tensor.device
|
641 |
+
sequence_length = input_tensor.shape[1]
|
642 |
+
if using_static_cache:
|
643 |
+
target_length = past_key_values.get_max_cache_shape()
|
644 |
+
else:
|
645 |
+
target_length = (
|
646 |
+
attention_mask.shape[-1]
|
647 |
+
if isinstance(attention_mask, torch.Tensor)
|
648 |
+
else past_seen_tokens + sequence_length + 1
|
649 |
+
)
|
650 |
+
|
651 |
+
# In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
|
652 |
+
causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
|
653 |
+
attention_mask,
|
654 |
+
sequence_length=sequence_length,
|
655 |
+
target_length=target_length,
|
656 |
+
dtype=dtype,
|
657 |
+
device=device,
|
658 |
+
cache_position=cache_position,
|
659 |
+
batch_size=input_tensor.shape[0],
|
660 |
+
)
|
661 |
+
|
662 |
+
if (
|
663 |
+
self.config._attn_implementation == "sdpa"
|
664 |
+
and attention_mask is not None
|
665 |
+
and attention_mask.device.type == "cuda"
|
666 |
+
and not output_attentions
|
667 |
+
):
|
668 |
+
# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
|
669 |
+
# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
|
670 |
+
# Details: https://github.com/pytorch/pytorch/issues/110213
|
671 |
+
min_dtype = torch.finfo(dtype).min
|
672 |
+
causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
|
673 |
+
|
674 |
+
return causal_mask
|
675 |
+
|
676 |
+
@staticmethod
|
677 |
+
def _prepare_4d_causal_attention_mask_with_cache_position(
|
678 |
+
attention_mask: torch.Tensor,
|
679 |
+
sequence_length: int,
|
680 |
+
target_length: int,
|
681 |
+
dtype: torch.dtype,
|
682 |
+
device: torch.device,
|
683 |
+
cache_position: torch.Tensor,
|
684 |
+
batch_size: int,
|
685 |
+
**kwargs,
|
686 |
+
):
|
687 |
+
"""
|
688 |
+
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
|
689 |
+
`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
|
690 |
+
|
691 |
+
Args:
|
692 |
+
attention_mask (`torch.Tensor`):
|
693 |
+
A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
|
694 |
+
`(batch_size, 1, query_length, key_value_length)`.
|
695 |
+
sequence_length (`int`):
|
696 |
+
The sequence length being processed.
|
697 |
+
target_length (`int`):
|
698 |
+
The target length: when generating with static cache, the mask should be as long as the static cache,
|
699 |
+
to account for the 0 padding, the part of the cache that is not filled yet.
|
700 |
+
dtype (`torch.dtype`):
|
701 |
+
The dtype to use for the 4D attention mask.
|
702 |
+
device (`torch.device`):
|
703 |
+
The device to plcae the 4D attention mask on.
|
704 |
+
cache_position (`torch.Tensor`):
|
705 |
+
Indices depicting the position of the input sequence tokens in the sequence.
|
706 |
+
batch_size (`torch.Tensor`):
|
707 |
+
Batch size.
|
708 |
+
"""
|
709 |
+
if attention_mask is not None and attention_mask.dim() == 4:
|
710 |
+
# In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
|
711 |
+
causal_mask = attention_mask
|
712 |
+
else:
|
713 |
+
min_dtype = torch.finfo(dtype).min
|
714 |
+
causal_mask = torch.full(
|
715 |
+
(sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
|
716 |
+
)
|
717 |
+
if sequence_length != 1:
|
718 |
+
causal_mask = torch.triu(causal_mask, diagonal=1)
|
719 |
+
causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
|
720 |
+
causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
|
721 |
+
if attention_mask is not None:
|
722 |
+
causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
|
723 |
+
mask_length = attention_mask.shape[-1]
|
724 |
+
padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
|
725 |
+
padding_mask = padding_mask == 0
|
726 |
+
causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
|
727 |
+
padding_mask, min_dtype
|
728 |
+
)
|
729 |
+
|
730 |
+
return causal_mask
|
731 |
+
|
732 |
+
|
733 |
+
class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
|
734 |
+
|
735 |
+
|
736 |
+
class Qwen2ForCausalLM(Qwen2PreTrainedModel, GenerationMixin):
|
737 |
+
_tied_weights_keys = ["lm_head.weight"]
|
738 |
+
_tp_plan = {"lm_head": "colwise_rep"}
|
739 |
+
|
740 |
+
def __init__(self, config):
|
741 |
+
super().__init__(config)
|
742 |
+
self.model = Qwen2Model(config)
|
743 |
+
self.vocab_size = config.vocab_size
|
744 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
745 |
+
|
746 |
+
# Initialize weights and apply final processing
|
747 |
+
self.post_init()
|
748 |
+
|
749 |
+
def get_input_embeddings(self):
|
750 |
+
return self.model.embed_tokens
|
751 |
+
|
752 |
+
def set_input_embeddings(self, value):
|
753 |
+
self.model.embed_tokens = value
|
754 |
+
|
755 |
+
def get_output_embeddings(self):
|
756 |
+
return self.lm_head
|
757 |
+
|
758 |
+
def set_output_embeddings(self, new_embeddings):
|
759 |
+
self.lm_head = new_embeddings
|
760 |
+
|
761 |
+
def set_decoder(self, decoder):
|
762 |
+
self.model = decoder
|
763 |
+
|
764 |
+
def get_decoder(self):
|
765 |
+
return self.model
|
766 |
+
|
767 |
+
@deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
|
768 |
+
@add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
|
769 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
770 |
+
def forward(
|
771 |
+
self,
|
772 |
+
input_ids: torch.LongTensor = None,
|
773 |
+
attention_mask: Optional[torch.Tensor] = None,
|
774 |
+
position_ids: Optional[torch.LongTensor] = None,
|
775 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
776 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
777 |
+
labels: Optional[torch.LongTensor] = None,
|
778 |
+
use_cache: Optional[bool] = None,
|
779 |
+
output_attentions: Optional[bool] = None,
|
780 |
+
output_hidden_states: Optional[bool] = None,
|
781 |
+
return_dict: Optional[bool] = None,
|
782 |
+
cache_position: Optional[torch.LongTensor] = None,
|
783 |
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
784 |
+
**kwargs: Unpack[KwargsForCausalLM],
|
785 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
786 |
+
r"""
|
787 |
+
Args:
|
788 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
789 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
790 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
791 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
792 |
+
|
793 |
+
logits_to_keep (`int` or `torch.Tensor`, *optional*):
|
794 |
+
If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
|
795 |
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
796 |
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
797 |
+
If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
|
798 |
+
This is useful when using packed tensor format (single dimension for batch and sequence length).
|
799 |
+
|
800 |
+
Returns:
|
801 |
+
|
802 |
+
Example:
|
803 |
+
|
804 |
+
```python
|
805 |
+
>>> from transformers import AutoTokenizer, Qwen2ForCausalLM
|
806 |
+
|
807 |
+
>>> model = Qwen2ForCausalLM.from_pretrained("meta-qwen2/Qwen2-2-7b-hf")
|
808 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("meta-qwen2/Qwen2-2-7b-hf")
|
809 |
+
|
810 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
811 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
812 |
+
|
813 |
+
>>> # Generate
|
814 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
815 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
816 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
817 |
+
```"""
|
818 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
819 |
+
output_hidden_states = (
|
820 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
821 |
+
)
|
822 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
823 |
+
|
824 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
825 |
+
outputs = self.model(
|
826 |
+
input_ids=input_ids,
|
827 |
+
attention_mask=attention_mask,
|
828 |
+
position_ids=position_ids,
|
829 |
+
past_key_values=past_key_values,
|
830 |
+
inputs_embeds=inputs_embeds,
|
831 |
+
use_cache=use_cache,
|
832 |
+
output_attentions=output_attentions,
|
833 |
+
output_hidden_states=output_hidden_states,
|
834 |
+
return_dict=return_dict,
|
835 |
+
cache_position=cache_position,
|
836 |
+
**kwargs,
|
837 |
+
)
|
838 |
+
|
839 |
+
hidden_states = outputs[0]
|
840 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
841 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
842 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
843 |
+
|
844 |
+
loss = None
|
845 |
+
if labels is not None:
|
846 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
847 |
+
|
848 |
+
if not return_dict:
|
849 |
+
output = (logits,) + outputs[1:]
|
850 |
+
return (loss,) + output if loss is not None else output
|
851 |
+
|
852 |
+
return CausalLMOutputWithPast(
|
853 |
+
loss=loss,
|
854 |
+
logits=logits,
|
855 |
+
past_key_values=outputs.past_key_values,
|
856 |
+
hidden_states=outputs.hidden_states,
|
857 |
+
attentions=outputs.attentions,
|
858 |
+
)
|
859 |
+
|
860 |
+
|
861 |
+
@add_start_docstrings(
|
862 |
+
"""
|
863 |
+
The Qwen2 Model transformer with a sequence classification head on top (linear layer).
|
864 |
+
|
865 |
+
[`Qwen2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
866 |
+
(e.g. GPT-2) do.
|
867 |
+
|
868 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
869 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
870 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
871 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
872 |
+
each row of the batch).
|
873 |
+
""",
|
874 |
+
QWEN2_START_DOCSTRING,
|
875 |
+
)
|
876 |
+
class Qwen2ForSequenceClassification(Qwen2PreTrainedModel):
|
877 |
+
def __init__(self, config):
|
878 |
+
super().__init__(config)
|
879 |
+
self.num_labels = config.num_labels
|
880 |
+
self.model = Qwen2Model(config)
|
881 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
882 |
+
|
883 |
+
# Initialize weights and apply final processing
|
884 |
+
self.post_init()
|
885 |
+
|
886 |
+
def get_input_embeddings(self):
|
887 |
+
return self.model.embed_tokens
|
888 |
+
|
889 |
+
def set_input_embeddings(self, value):
|
890 |
+
self.model.embed_tokens = value
|
891 |
+
|
892 |
+
@add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
|
893 |
+
def forward(
|
894 |
+
self,
|
895 |
+
input_ids: Optional[torch.LongTensor] = None,
|
896 |
+
attention_mask: Optional[torch.Tensor] = None,
|
897 |
+
position_ids: Optional[torch.LongTensor] = None,
|
898 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
899 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
900 |
+
labels: Optional[torch.LongTensor] = None,
|
901 |
+
use_cache: Optional[bool] = None,
|
902 |
+
output_attentions: Optional[bool] = None,
|
903 |
+
output_hidden_states: Optional[bool] = None,
|
904 |
+
return_dict: Optional[bool] = None,
|
905 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
906 |
+
r"""
|
907 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
908 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
909 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
910 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
911 |
+
"""
|
912 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
913 |
+
|
914 |
+
transformer_outputs = self.model(
|
915 |
+
input_ids,
|
916 |
+
attention_mask=attention_mask,
|
917 |
+
position_ids=position_ids,
|
918 |
+
past_key_values=past_key_values,
|
919 |
+
inputs_embeds=inputs_embeds,
|
920 |
+
use_cache=use_cache,
|
921 |
+
output_attentions=output_attentions,
|
922 |
+
output_hidden_states=output_hidden_states,
|
923 |
+
return_dict=return_dict,
|
924 |
+
)
|
925 |
+
hidden_states = transformer_outputs[0]
|
926 |
+
logits = self.score(hidden_states)
|
927 |
+
|
928 |
+
if input_ids is not None:
|
929 |
+
batch_size = input_ids.shape[0]
|
930 |
+
else:
|
931 |
+
batch_size = inputs_embeds.shape[0]
|
932 |
+
|
933 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
934 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
935 |
+
if self.config.pad_token_id is None:
|
936 |
+
sequence_lengths = -1
|
937 |
+
else:
|
938 |
+
if input_ids is not None:
|
939 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
940 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
941 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
942 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
943 |
+
else:
|
944 |
+
sequence_lengths = -1
|
945 |
+
|
946 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
947 |
+
|
948 |
+
loss = None
|
949 |
+
if labels is not None:
|
950 |
+
loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
|
951 |
+
|
952 |
+
if not return_dict:
|
953 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
954 |
+
return ((loss,) + output) if loss is not None else output
|
955 |
+
|
956 |
+
return SequenceClassifierOutputWithPast(
|
957 |
+
loss=loss,
|
958 |
+
logits=pooled_logits,
|
959 |
+
past_key_values=transformer_outputs.past_key_values,
|
960 |
+
hidden_states=transformer_outputs.hidden_states,
|
961 |
+
attentions=transformer_outputs.attentions,
|
962 |
+
)
|
963 |
+
|
964 |
+
|
965 |
+
@add_start_docstrings(
|
966 |
+
"""
|
967 |
+
The Qwen2 Model transformer with a token classification head on top (a linear layer on top of the hidden-states
|
968 |
+
output) e.g. for Named-Entity-Recognition (NER) tasks.
|
969 |
+
""",
|
970 |
+
QWEN2_START_DOCSTRING,
|
971 |
+
)
|
972 |
+
class Qwen2ForTokenClassification(Qwen2PreTrainedModel):
|
973 |
+
def __init__(self, config):
|
974 |
+
super().__init__(config)
|
975 |
+
self.num_labels = config.num_labels
|
976 |
+
self.model = Qwen2Model(config)
|
977 |
+
if getattr(config, "classifier_dropout", None) is not None:
|
978 |
+
classifier_dropout = config.classifier_dropout
|
979 |
+
elif getattr(config, "hidden_dropout", None) is not None:
|
980 |
+
classifier_dropout = config.hidden_dropout
|
981 |
+
else:
|
982 |
+
classifier_dropout = 0.1
|
983 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
984 |
+
self.score = nn.Linear(config.hidden_size, config.num_labels)
|
985 |
+
|
986 |
+
# Initialize weights and apply final processing
|
987 |
+
self.post_init()
|
988 |
+
|
989 |
+
def get_input_embeddings(self):
|
990 |
+
return self.model.embed_tokens
|
991 |
+
|
992 |
+
def set_input_embeddings(self, value):
|
993 |
+
self.model.embed_tokens = value
|
994 |
+
|
995 |
+
@add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
|
996 |
+
@add_code_sample_docstrings(
|
997 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
998 |
+
output_type=TokenClassifierOutput,
|
999 |
+
config_class=_CONFIG_FOR_DOC,
|
1000 |
+
)
|
1001 |
+
def forward(
|
1002 |
+
self,
|
1003 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1004 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1005 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1006 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1007 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1008 |
+
labels: Optional[torch.LongTensor] = None,
|
1009 |
+
use_cache: Optional[bool] = None,
|
1010 |
+
output_attentions: Optional[bool] = None,
|
1011 |
+
output_hidden_states: Optional[bool] = None,
|
1012 |
+
return_dict: Optional[bool] = None,
|
1013 |
+
) -> Union[Tuple, TokenClassifierOutput]:
|
1014 |
+
r"""
|
1015 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1016 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1017 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1018 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1019 |
+
"""
|
1020 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1021 |
+
|
1022 |
+
outputs = self.model(
|
1023 |
+
input_ids,
|
1024 |
+
attention_mask=attention_mask,
|
1025 |
+
position_ids=position_ids,
|
1026 |
+
past_key_values=past_key_values,
|
1027 |
+
inputs_embeds=inputs_embeds,
|
1028 |
+
use_cache=use_cache,
|
1029 |
+
output_attentions=output_attentions,
|
1030 |
+
output_hidden_states=output_hidden_states,
|
1031 |
+
return_dict=return_dict,
|
1032 |
+
)
|
1033 |
+
sequence_output = outputs[0]
|
1034 |
+
sequence_output = self.dropout(sequence_output)
|
1035 |
+
logits = self.score(sequence_output)
|
1036 |
+
|
1037 |
+
loss = None
|
1038 |
+
if labels is not None:
|
1039 |
+
loss = self.loss_function(logits, labels, self.config)
|
1040 |
+
|
1041 |
+
if not return_dict:
|
1042 |
+
output = (logits,) + outputs[2:]
|
1043 |
+
return ((loss,) + output) if loss is not None else output
|
1044 |
+
|
1045 |
+
return TokenClassifierOutput(
|
1046 |
+
loss=loss,
|
1047 |
+
logits=logits,
|
1048 |
+
hidden_states=outputs.hidden_states,
|
1049 |
+
attentions=outputs.attentions,
|
1050 |
+
)
|
1051 |
+
|
1052 |
+
|
1053 |
+
@add_start_docstrings(
|
1054 |
+
"""
|
1055 |
+
The Qwen2 Model transformer with a span classification head on top for extractive question-answering tasks like
|
1056 |
+
SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
1057 |
+
""",
|
1058 |
+
QWEN2_START_DOCSTRING,
|
1059 |
+
)
|
1060 |
+
class Qwen2ForQuestionAnswering(Qwen2PreTrainedModel):
|
1061 |
+
base_model_prefix = "transformer"
|
1062 |
+
|
1063 |
+
def __init__(self, config):
|
1064 |
+
super().__init__(config)
|
1065 |
+
self.transformer = Qwen2Model(config)
|
1066 |
+
self.qa_outputs = nn.Linear(config.hidden_size, 2)
|
1067 |
+
|
1068 |
+
# Initialize weights and apply final processing
|
1069 |
+
self.post_init()
|
1070 |
+
|
1071 |
+
def get_input_embeddings(self):
|
1072 |
+
return self.transformer.embed_tokens
|
1073 |
+
|
1074 |
+
def set_input_embeddings(self, value):
|
1075 |
+
self.transformer.embed_tokens = value
|
1076 |
+
|
1077 |
+
@add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
|
1078 |
+
def forward(
|
1079 |
+
self,
|
1080 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1081 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
1082 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1083 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
1084 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1085 |
+
start_positions: Optional[torch.LongTensor] = None,
|
1086 |
+
end_positions: Optional[torch.LongTensor] = None,
|
1087 |
+
output_attentions: Optional[bool] = None,
|
1088 |
+
output_hidden_states: Optional[bool] = None,
|
1089 |
+
return_dict: Optional[bool] = None,
|
1090 |
+
**kwargs,
|
1091 |
+
) -> Union[Tuple, QuestionAnsweringModelOutput]:
|
1092 |
+
r"""
|
1093 |
+
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1094 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
1095 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
1096 |
+
are not taken into account for computing the loss.
|
1097 |
+
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1098 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
1099 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
1100 |
+
are not taken into account for computing the loss.
|
1101 |
+
"""
|
1102 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1103 |
+
|
1104 |
+
outputs = self.transformer(
|
1105 |
+
input_ids,
|
1106 |
+
attention_mask=attention_mask,
|
1107 |
+
position_ids=position_ids,
|
1108 |
+
past_key_values=past_key_values,
|
1109 |
+
inputs_embeds=inputs_embeds,
|
1110 |
+
output_attentions=output_attentions,
|
1111 |
+
output_hidden_states=output_hidden_states,
|
1112 |
+
return_dict=return_dict,
|
1113 |
+
)
|
1114 |
+
|
1115 |
+
sequence_output = outputs[0]
|
1116 |
+
|
1117 |
+
logits = self.qa_outputs(sequence_output)
|
1118 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
1119 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
1120 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
1121 |
+
|
1122 |
+
loss = None
|
1123 |
+
if start_positions is not None and end_positions is not None:
|
1124 |
+
loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
|
1125 |
+
|
1126 |
+
if not return_dict:
|
1127 |
+
output = (start_logits, end_logits) + outputs[2:]
|
1128 |
+
return ((loss,) + output) if loss is not None else output
|
1129 |
+
|
1130 |
+
return QuestionAnsweringModelOutput(
|
1131 |
+
loss=loss,
|
1132 |
+
start_logits=start_logits,
|
1133 |
+
end_logits=end_logits,
|
1134 |
+
hidden_states=outputs.hidden_states,
|
1135 |
+
attentions=outputs.attentions,
|
1136 |
+
)
|
Qwen2.5-3B-512k-lc-39iters/tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
Qwen2.5-3B-512k-lc-39iters/tokenizer_config.json
ADDED
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"add_bos_token": false,
|
3 |
+
"add_prefix_space": false,
|
4 |
+
"added_tokens_decoder": {
|
5 |
+
"151643": {
|
6 |
+
"content": "<|endoftext|>",
|
7 |
+
"lstrip": false,
|
8 |
+
"normalized": false,
|
9 |
+
"rstrip": false,
|
10 |
+
"single_word": false,
|
11 |
+
"special": true
|
12 |
+
},
|
13 |
+
"151644": {
|
14 |
+
"content": "<|im_start|>",
|
15 |
+
"lstrip": false,
|
16 |
+
"normalized": false,
|
17 |
+
"rstrip": false,
|
18 |
+
"single_word": false,
|
19 |
+
"special": true
|
20 |
+
},
|
21 |
+
"151645": {
|
22 |
+
"content": "<|im_end|>",
|
23 |
+
"lstrip": false,
|
24 |
+
"normalized": false,
|
25 |
+
"rstrip": false,
|
26 |
+
"single_word": false,
|
27 |
+
"special": true
|
28 |
+
},
|
29 |
+
"151646": {
|
30 |
+
"content": "<|object_ref_start|>",
|
31 |
+
"lstrip": false,
|
32 |
+
"normalized": false,
|
33 |
+
"rstrip": false,
|
34 |
+
"single_word": false,
|
35 |
+
"special": true
|
36 |
+
},
|
37 |
+
"151647": {
|
38 |
+
"content": "<|object_ref_end|>",
|
39 |
+
"lstrip": false,
|
40 |
+
"normalized": false,
|
41 |
+
"rstrip": false,
|
42 |
+
"single_word": false,
|
43 |
+
"special": true
|
44 |
+
},
|
45 |
+
"151648": {
|
46 |
+
"content": "<|box_start|>",
|
47 |
+
"lstrip": false,
|
48 |
+
"normalized": false,
|
49 |
+
"rstrip": false,
|
50 |
+
"single_word": false,
|
51 |
+
"special": true
|
52 |
+
},
|
53 |
+
"151649": {
|
54 |
+
"content": "<|box_end|>",
|
55 |
+
"lstrip": false,
|
56 |
+
"normalized": false,
|
57 |
+
"rstrip": false,
|
58 |
+
"single_word": false,
|
59 |
+
"special": true
|
60 |
+
},
|
61 |
+
"151650": {
|
62 |
+
"content": "<|quad_start|>",
|
63 |
+
"lstrip": false,
|
64 |
+
"normalized": false,
|
65 |
+
"rstrip": false,
|
66 |
+
"single_word": false,
|
67 |
+
"special": true
|
68 |
+
},
|
69 |
+
"151651": {
|
70 |
+
"content": "<|quad_end|>",
|
71 |
+
"lstrip": false,
|
72 |
+
"normalized": false,
|
73 |
+
"rstrip": false,
|
74 |
+
"single_word": false,
|
75 |
+
"special": true
|
76 |
+
},
|
77 |
+
"151652": {
|
78 |
+
"content": "<|vision_start|>",
|
79 |
+
"lstrip": false,
|
80 |
+
"normalized": false,
|
81 |
+
"rstrip": false,
|
82 |
+
"single_word": false,
|
83 |
+
"special": true
|
84 |
+
},
|
85 |
+
"151653": {
|
86 |
+
"content": "<|vision_end|>",
|
87 |
+
"lstrip": false,
|
88 |
+
"normalized": false,
|
89 |
+
"rstrip": false,
|
90 |
+
"single_word": false,
|
91 |
+
"special": true
|
92 |
+
},
|
93 |
+
"151654": {
|
94 |
+
"content": "<|vision_pad|>",
|
95 |
+
"lstrip": false,
|
96 |
+
"normalized": false,
|
97 |
+
"rstrip": false,
|
98 |
+
"single_word": false,
|
99 |
+
"special": true
|
100 |
+
},
|
101 |
+
"151655": {
|
102 |
+
"content": "<|image_pad|>",
|
103 |
+
"lstrip": false,
|
104 |
+
"normalized": false,
|
105 |
+
"rstrip": false,
|
106 |
+
"single_word": false,
|
107 |
+
"special": true
|
108 |
+
},
|
109 |
+
"151656": {
|
110 |
+
"content": "<|video_pad|>",
|
111 |
+
"lstrip": false,
|
112 |
+
"normalized": false,
|
113 |
+
"rstrip": false,
|
114 |
+
"single_word": false,
|
115 |
+
"special": true
|
116 |
+
},
|
117 |
+
"151657": {
|
118 |
+
"content": "<tool_call>",
|
119 |
+
"lstrip": false,
|
120 |
+
"normalized": false,
|
121 |
+
"rstrip": false,
|
122 |
+
"single_word": false,
|
123 |
+
"special": false
|
124 |
+
},
|
125 |
+
"151658": {
|
126 |
+
"content": "</tool_call>",
|
127 |
+
"lstrip": false,
|
128 |
+
"normalized": false,
|
129 |
+
"rstrip": false,
|
130 |
+
"single_word": false,
|
131 |
+
"special": false
|
132 |
+
},
|
133 |
+
"151659": {
|
134 |
+
"content": "<|fim_prefix|>",
|
135 |
+
"lstrip": false,
|
136 |
+
"normalized": false,
|
137 |
+
"rstrip": false,
|
138 |
+
"single_word": false,
|
139 |
+
"special": false
|
140 |
+
},
|
141 |
+
"151660": {
|
142 |
+
"content": "<|fim_middle|>",
|
143 |
+
"lstrip": false,
|
144 |
+
"normalized": false,
|
145 |
+
"rstrip": false,
|
146 |
+
"single_word": false,
|
147 |
+
"special": false
|
148 |
+
},
|
149 |
+
"151661": {
|
150 |
+
"content": "<|fim_suffix|>",
|
151 |
+
"lstrip": false,
|
152 |
+
"normalized": false,
|
153 |
+
"rstrip": false,
|
154 |
+
"single_word": false,
|
155 |
+
"special": false
|
156 |
+
},
|
157 |
+
"151662": {
|
158 |
+
"content": "<|fim_pad|>",
|
159 |
+
"lstrip": false,
|
160 |
+
"normalized": false,
|
161 |
+
"rstrip": false,
|
162 |
+
"single_word": false,
|
163 |
+
"special": false
|
164 |
+
},
|
165 |
+
"151663": {
|
166 |
+
"content": "<|repo_name|>",
|
167 |
+
"lstrip": false,
|
168 |
+
"normalized": false,
|
169 |
+
"rstrip": false,
|
170 |
+
"single_word": false,
|
171 |
+
"special": false
|
172 |
+
},
|
173 |
+
"151664": {
|
174 |
+
"content": "<|file_sep|>",
|
175 |
+
"lstrip": false,
|
176 |
+
"normalized": false,
|
177 |
+
"rstrip": false,
|
178 |
+
"single_word": false,
|
179 |
+
"special": false
|
180 |
+
}
|
181 |
+
},
|
182 |
+
"additional_special_tokens": [
|
183 |
+
"<|im_start|>",
|
184 |
+
"<|im_end|>",
|
185 |
+
"<|object_ref_start|>",
|
186 |
+
"<|object_ref_end|>",
|
187 |
+
"<|box_start|>",
|
188 |
+
"<|box_end|>",
|
189 |
+
"<|quad_start|>",
|
190 |
+
"<|quad_end|>",
|
191 |
+
"<|vision_start|>",
|
192 |
+
"<|vision_end|>",
|
193 |
+
"<|vision_pad|>",
|
194 |
+
"<|image_pad|>",
|
195 |
+
"<|video_pad|>"
|
196 |
+
],
|
197 |
+
"bos_token": null,
|
198 |
+
"chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0]['role'] == 'system' %}\n {{- messages[0]['content'] }}\n {%- else %}\n {{- 'You are a helpful assistant.' }}\n {%- endif %}\n {{- \"\\n\\n# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n {%- if messages[0]['role'] == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0]['content'] + '<|im_end|>\\n' }}\n {%- else %}\n {{- '<|im_start|>system\\nYou are a helpful assistant.<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- for message in messages %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) or (message.role == \"assistant\" and not message.tool_calls) %}\n {{- '<|im_start|>' + message.role + '\\n' + message.content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {{- '<|im_start|>' + message.role }}\n {%- if message.content %}\n {{- '\\n' + message.content }}\n {%- endif %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '\\n<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {{- tool_call.arguments | tojson }}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- message.content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n{%- endif %}\n",
|
199 |
+
"clean_up_tokenization_spaces": false,
|
200 |
+
"eos_token": "<|endoftext|>",
|
201 |
+
"errors": "replace",
|
202 |
+
"model_max_length": 524288,
|
203 |
+
"pad_token": "<|endoftext|>",
|
204 |
+
"split_special_tokens": false,
|
205 |
+
"tokenizer_class": "Qwen2Tokenizer",
|
206 |
+
"unk_token": null
|
207 |
+
}
|
Qwen2.5-3B-512k-lc-39iters/vocab.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
Qwen2.5-3B-512k-mi-flexpf_090-39iters-2025041801/config.json
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"Qwen2ForCausalLM"
|
4 |
+
],
|
5 |
+
"attention_dropout": 0.0,
|
6 |
+
"bos_token_id": 151643,
|
7 |
+
"eos_token_id": 151643,
|
8 |
+
"hidden_act": "silu",
|
9 |
+
"hidden_size": 2048,
|
10 |
+
"initializer_range": 0.02,
|
11 |
+
"intermediate_size": 11008,
|
12 |
+
"max_position_embeddings": 524288,
|
13 |
+
"rope_scaling": {
|
14 |
+
"factor": 16.0,
|
15 |
+
"original_max_position_embeddings": 32768,
|
16 |
+
"type": "yarn"
|
17 |
+
},
|
18 |
+
"max_window_layers": 36,
|
19 |
+
"model_type": "qwen2",
|
20 |
+
"num_attention_heads": 16,
|
21 |
+
"num_hidden_layers": 36,
|
22 |
+
"num_key_value_heads": 2,
|
23 |
+
"rms_norm_eps": 1e-06,
|
24 |
+
"rope_theta": 1000000.0,
|
25 |
+
"sliding_window": 32768,
|
26 |
+
"tie_word_embeddings": true,
|
27 |
+
"torch_dtype": "bfloat16",
|
28 |
+
"transformers_version": "4.40.1",
|
29 |
+
"use_cache": true,
|
30 |
+
"use_mrope": false,
|
31 |
+
"use_sliding_window": false,
|
32 |
+
"vocab_size": 151936
|
33 |
+
}
|
Qwen2.5-3B-512k-mi-flexpf_090-39iters-2025041801/generation_config.json
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token_id": 151643,
|
3 |
+
"do_sample": false,
|
4 |
+
"eos_token_id": 151643,
|
5 |
+
"max_new_tokens": 2048,
|
6 |
+
"transformers_version": "4.37.0"
|
7 |
+
}
|
Qwen2.5-3B-512k-mi-flexpf_090-39iters-2025041801/modeling_qwen2.py
ADDED
@@ -0,0 +1,1136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
2 |
+
# This file was automatically generated from src/transformers/models/qwen2/modular_qwen2.py.
|
3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
5 |
+
# modular_qwen2.py file directly. One of our CI enforces this.
|
6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
7 |
+
from typing import Callable, List, Optional, Tuple, Union
|
8 |
+
|
9 |
+
import torch
|
10 |
+
from torch import nn
|
11 |
+
|
12 |
+
from transformers.activations import ACT2FN
|
13 |
+
from transformers.cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCache
|
14 |
+
from transformers.generation import GenerationMixin
|
15 |
+
from transformers.modeling_attn_mask_utils import AttentionMaskConverter
|
16 |
+
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
|
17 |
+
from transformers.modeling_outputs import (
|
18 |
+
BaseModelOutputWithPast,
|
19 |
+
CausalLMOutputWithPast,
|
20 |
+
SequenceClassifierOutputWithPast,
|
21 |
+
QuestionAnsweringModelOutput,
|
22 |
+
TokenClassifierOutput,
|
23 |
+
)
|
24 |
+
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
|
25 |
+
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
26 |
+
from transformers.processing_utils import Unpack
|
27 |
+
from transformers.utils import (
|
28 |
+
LossKwargs,
|
29 |
+
add_code_sample_docstrings,
|
30 |
+
add_start_docstrings,
|
31 |
+
add_start_docstrings_to_model_forward,
|
32 |
+
logging,
|
33 |
+
replace_return_docstrings,
|
34 |
+
)
|
35 |
+
from transformers.utils.deprecation import deprecate_kwarg
|
36 |
+
from .configuration_qwen2 import Qwen2Config
|
37 |
+
|
38 |
+
|
39 |
+
logger = logging.get_logger(__name__)
|
40 |
+
|
41 |
+
_CHECKPOINT_FOR_DOC = "meta-qwen2/Qwen2-2-7b-hf"
|
42 |
+
_CONFIG_FOR_DOC = "Qwen2Config"
|
43 |
+
|
44 |
+
QWEN_ATTN_FUNCS = ALL_ATTENTION_FUNCTIONS.copy()
|
45 |
+
|
46 |
+
class Qwen2MLP(nn.Module):
|
47 |
+
def __init__(self, config):
|
48 |
+
super().__init__()
|
49 |
+
self.config = config
|
50 |
+
self.hidden_size = config.hidden_size
|
51 |
+
self.intermediate_size = config.intermediate_size
|
52 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
53 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
54 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
55 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
56 |
+
|
57 |
+
def forward(self, x):
|
58 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
59 |
+
return down_proj
|
60 |
+
|
61 |
+
|
62 |
+
def rotate_half(x):
|
63 |
+
"""Rotates half the hidden dims of the input."""
|
64 |
+
x1 = x[..., : x.shape[-1] // 2]
|
65 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
66 |
+
return torch.cat((-x2, x1), dim=-1)
|
67 |
+
|
68 |
+
|
69 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
70 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
71 |
+
|
72 |
+
Args:
|
73 |
+
q (`torch.Tensor`): The query tensor.
|
74 |
+
k (`torch.Tensor`): The key tensor.
|
75 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
76 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
77 |
+
position_ids (`torch.Tensor`, *optional*):
|
78 |
+
Deprecated and unused.
|
79 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
80 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
81 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
82 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
83 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
84 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
85 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
86 |
+
Returns:
|
87 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
88 |
+
"""
|
89 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
90 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
91 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
92 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
93 |
+
return q_embed, k_embed
|
94 |
+
|
95 |
+
|
96 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
97 |
+
"""
|
98 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
99 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
100 |
+
"""
|
101 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
102 |
+
if n_rep == 1:
|
103 |
+
return hidden_states
|
104 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
105 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
106 |
+
|
107 |
+
|
108 |
+
def eager_attention_forward(
|
109 |
+
module: nn.Module,
|
110 |
+
query: torch.Tensor,
|
111 |
+
key: torch.Tensor,
|
112 |
+
value: torch.Tensor,
|
113 |
+
attention_mask: Optional[torch.Tensor],
|
114 |
+
scaling: float,
|
115 |
+
dropout: float = 0.0,
|
116 |
+
**kwargs,
|
117 |
+
):
|
118 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
119 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
120 |
+
|
121 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
122 |
+
if attention_mask is not None:
|
123 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
124 |
+
attn_weights = attn_weights + causal_mask
|
125 |
+
|
126 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
127 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
128 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
129 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
130 |
+
|
131 |
+
return attn_output, attn_weights
|
132 |
+
|
133 |
+
|
134 |
+
class Qwen2Attention(nn.Module):
|
135 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
136 |
+
|
137 |
+
def __init__(self, config: Qwen2Config, layer_idx: int):
|
138 |
+
super().__init__()
|
139 |
+
self.config = config
|
140 |
+
self.layer_idx = layer_idx
|
141 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
142 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
143 |
+
self.scaling = self.head_dim**-0.5
|
144 |
+
self.attention_dropout = config.attention_dropout
|
145 |
+
self.is_causal = True
|
146 |
+
self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=True)
|
147 |
+
self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
|
148 |
+
self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
|
149 |
+
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
|
150 |
+
|
151 |
+
def forward(
|
152 |
+
self,
|
153 |
+
hidden_states: torch.Tensor,
|
154 |
+
position_embeddings: Tuple[torch.Tensor, torch.Tensor],
|
155 |
+
attention_mask: Optional[torch.Tensor],
|
156 |
+
past_key_value: Optional[Cache] = None,
|
157 |
+
cache_position: Optional[torch.LongTensor] = None,
|
158 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
159 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
160 |
+
input_shape = hidden_states.shape[:-1]
|
161 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
162 |
+
|
163 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
164 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
165 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
166 |
+
|
167 |
+
cos, sin = position_embeddings
|
168 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
169 |
+
|
170 |
+
if past_key_value is not None:
|
171 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
172 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
173 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
174 |
+
|
175 |
+
sliding_window = None
|
176 |
+
if (
|
177 |
+
self.config.use_sliding_window
|
178 |
+
and getattr(self.config, "sliding_window", None) is not None
|
179 |
+
and self.layer_idx >= self.config.max_window_layers
|
180 |
+
):
|
181 |
+
sliding_window = self.config.sliding_window
|
182 |
+
|
183 |
+
attention_interface: Callable = eager_attention_forward
|
184 |
+
if self.config._attn_implementation != "eager":
|
185 |
+
if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
|
186 |
+
logger.warning_once(
|
187 |
+
"`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
|
188 |
+
'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
189 |
+
)
|
190 |
+
else:
|
191 |
+
attention_interface = QWEN_ATTN_FUNCS[self.config._attn_implementation]
|
192 |
+
|
193 |
+
attn_output, attn_weights = attention_interface(
|
194 |
+
self,
|
195 |
+
query_states,
|
196 |
+
key_states,
|
197 |
+
value_states,
|
198 |
+
attention_mask,
|
199 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
200 |
+
scaling=self.scaling,
|
201 |
+
sliding_window=sliding_window, # main diff with Llama
|
202 |
+
**kwargs,
|
203 |
+
)
|
204 |
+
|
205 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
206 |
+
attn_output = self.o_proj(attn_output)
|
207 |
+
return attn_output, attn_weights
|
208 |
+
|
209 |
+
|
210 |
+
class Qwen2RMSNorm(nn.Module):
|
211 |
+
def __init__(self, hidden_size, eps=1e-6):
|
212 |
+
"""
|
213 |
+
Qwen2RMSNorm is equivalent to T5LayerNorm
|
214 |
+
"""
|
215 |
+
super().__init__()
|
216 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
217 |
+
self.variance_epsilon = eps
|
218 |
+
|
219 |
+
def forward(self, hidden_states):
|
220 |
+
input_dtype = hidden_states.dtype
|
221 |
+
hidden_states = hidden_states.to(torch.float32)
|
222 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
223 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
224 |
+
return self.weight * hidden_states.to(input_dtype)
|
225 |
+
|
226 |
+
def extra_repr(self):
|
227 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
228 |
+
|
229 |
+
|
230 |
+
class Qwen2DecoderLayer(nn.Module):
|
231 |
+
def __init__(self, config: Qwen2Config, layer_idx: int):
|
232 |
+
super().__init__()
|
233 |
+
self.hidden_size = config.hidden_size
|
234 |
+
self.self_attn = Qwen2Attention(config=config, layer_idx=layer_idx)
|
235 |
+
self.mlp = Qwen2MLP(config)
|
236 |
+
self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
237 |
+
self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
238 |
+
if config.sliding_window and config._attn_implementation != "flash_attention_2":
|
239 |
+
logger.warning_once(
|
240 |
+
f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
|
241 |
+
"unexpected results may be encountered."
|
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: Optional[bool] = False,
|
251 |
+
use_cache: Optional[bool] = False,
|
252 |
+
cache_position: Optional[torch.LongTensor] = None,
|
253 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
|
254 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
255 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
256 |
+
residual = hidden_states
|
257 |
+
|
258 |
+
hidden_states = self.input_layernorm(hidden_states)
|
259 |
+
|
260 |
+
# Self Attention
|
261 |
+
hidden_states, self_attn_weights = self.self_attn(
|
262 |
+
hidden_states=hidden_states,
|
263 |
+
attention_mask=attention_mask,
|
264 |
+
position_ids=position_ids,
|
265 |
+
past_key_value=past_key_value,
|
266 |
+
output_attentions=output_attentions,
|
267 |
+
use_cache=use_cache,
|
268 |
+
cache_position=cache_position,
|
269 |
+
position_embeddings=position_embeddings,
|
270 |
+
**kwargs,
|
271 |
+
)
|
272 |
+
hidden_states = residual + hidden_states
|
273 |
+
|
274 |
+
# Fully Connected
|
275 |
+
residual = hidden_states
|
276 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
277 |
+
hidden_states = self.mlp(hidden_states)
|
278 |
+
hidden_states = residual + hidden_states
|
279 |
+
|
280 |
+
outputs = (hidden_states,)
|
281 |
+
if output_attentions:
|
282 |
+
outputs += (self_attn_weights,)
|
283 |
+
|
284 |
+
return outputs
|
285 |
+
|
286 |
+
|
287 |
+
class Qwen2RotaryEmbedding(nn.Module):
|
288 |
+
def __init__(self, config: Qwen2Config, device=None):
|
289 |
+
super().__init__()
|
290 |
+
# BC: "rope_type" was originally "type"
|
291 |
+
if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
|
292 |
+
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
293 |
+
else:
|
294 |
+
self.rope_type = "default"
|
295 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
296 |
+
self.original_max_seq_len = config.max_position_embeddings
|
297 |
+
|
298 |
+
self.config = config
|
299 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
300 |
+
|
301 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
|
302 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
303 |
+
self.original_inv_freq = self.inv_freq
|
304 |
+
|
305 |
+
def _dynamic_frequency_update(self, position_ids, device):
|
306 |
+
"""
|
307 |
+
dynamic RoPE layers should recompute `inv_freq` in the following situations:
|
308 |
+
1 - growing beyond the cached sequence length (allow scaling)
|
309 |
+
2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
|
310 |
+
"""
|
311 |
+
seq_len = torch.max(position_ids) + 1
|
312 |
+
if seq_len > self.max_seq_len_cached: # growth
|
313 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
|
314 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
|
315 |
+
self.max_seq_len_cached = seq_len
|
316 |
+
|
317 |
+
if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
|
318 |
+
# This .to() is needed if the model has been moved to a device after being initialized (because
|
319 |
+
# the buffer is automatically moved, but not the original copy)
|
320 |
+
self.original_inv_freq = self.original_inv_freq.to(device)
|
321 |
+
self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
|
322 |
+
self.max_seq_len_cached = self.original_max_seq_len
|
323 |
+
|
324 |
+
@torch.no_grad()
|
325 |
+
def forward(self, x, position_ids):
|
326 |
+
if "dynamic" in self.rope_type:
|
327 |
+
self._dynamic_frequency_update(position_ids, device=x.device)
|
328 |
+
|
329 |
+
# Core RoPE block
|
330 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
331 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
332 |
+
# Force float32 (see https://github.com/huggingface/transformers/pull/29285)
|
333 |
+
device_type = x.device.type
|
334 |
+
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
|
335 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
336 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
337 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
338 |
+
cos = emb.cos()
|
339 |
+
sin = emb.sin()
|
340 |
+
|
341 |
+
# Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
|
342 |
+
cos = cos * self.attention_scaling
|
343 |
+
sin = sin * self.attention_scaling
|
344 |
+
|
345 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
346 |
+
|
347 |
+
|
348 |
+
QWEN2_START_DOCSTRING = r"""
|
349 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
350 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
351 |
+
etc.)
|
352 |
+
|
353 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
354 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
355 |
+
and behavior.
|
356 |
+
|
357 |
+
Parameters:
|
358 |
+
config ([`Qwen2Config`]):
|
359 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
360 |
+
load the weights associated with the model, only the configuration. Check out the
|
361 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
362 |
+
"""
|
363 |
+
|
364 |
+
|
365 |
+
@add_start_docstrings(
|
366 |
+
"The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
|
367 |
+
QWEN2_START_DOCSTRING,
|
368 |
+
)
|
369 |
+
class Qwen2PreTrainedModel(PreTrainedModel):
|
370 |
+
config_class = Qwen2Config
|
371 |
+
base_model_prefix = "model"
|
372 |
+
supports_gradient_checkpointing = True
|
373 |
+
_no_split_modules = ["Qwen2DecoderLayer"]
|
374 |
+
_skip_keys_device_placement = ["past_key_values"]
|
375 |
+
_supports_flash_attn_2 = True
|
376 |
+
_supports_sdpa = True
|
377 |
+
_supports_flex_attn = True
|
378 |
+
_supports_cache_class = True
|
379 |
+
_supports_quantized_cache = True
|
380 |
+
_supports_static_cache = True
|
381 |
+
_supports_attention_backend = True
|
382 |
+
|
383 |
+
def _init_weights(self, module):
|
384 |
+
std = self.config.initializer_range
|
385 |
+
if isinstance(module, nn.Linear):
|
386 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
387 |
+
if module.bias is not None:
|
388 |
+
module.bias.data.zero_()
|
389 |
+
elif isinstance(module, nn.Embedding):
|
390 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
391 |
+
if module.padding_idx is not None:
|
392 |
+
module.weight.data[module.padding_idx].zero_()
|
393 |
+
|
394 |
+
|
395 |
+
QWEN2_INPUTS_DOCSTRING = r"""
|
396 |
+
Args:
|
397 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
398 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
399 |
+
it.
|
400 |
+
|
401 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
402 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
403 |
+
|
404 |
+
[What are input IDs?](../glossary#input-ids)
|
405 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
406 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
407 |
+
|
408 |
+
- 1 for tokens that are **not masked**,
|
409 |
+
- 0 for tokens that are **masked**.
|
410 |
+
|
411 |
+
[What are attention masks?](../glossary#attention-mask)
|
412 |
+
|
413 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
414 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
415 |
+
|
416 |
+
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
|
417 |
+
`past_key_values`).
|
418 |
+
|
419 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
420 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
421 |
+
information on the default strategy.
|
422 |
+
|
423 |
+
- 1 indicates the head is **not masked**,
|
424 |
+
- 0 indicates the head is **masked**.
|
425 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
426 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
427 |
+
config.n_positions - 1]`.
|
428 |
+
|
429 |
+
[What are position IDs?](../glossary#position-ids)
|
430 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
431 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
432 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
433 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
434 |
+
|
435 |
+
Two formats are allowed:
|
436 |
+
- a [`~cache_utils.Cache`] instance, see our
|
437 |
+
[kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
|
438 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
439 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
440 |
+
cache format.
|
441 |
+
|
442 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
443 |
+
legacy cache format will be returned.
|
444 |
+
|
445 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
446 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
447 |
+
of shape `(batch_size, sequence_length)`.
|
448 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
449 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
450 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
451 |
+
model's internal embedding lookup matrix.
|
452 |
+
use_cache (`bool`, *optional*):
|
453 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
454 |
+
`past_key_values`).
|
455 |
+
output_attentions (`bool`, *optional*):
|
456 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
457 |
+
tensors for more detail.
|
458 |
+
output_hidden_states (`bool`, *optional*):
|
459 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
460 |
+
more detail.
|
461 |
+
return_dict (`bool`, *optional*):
|
462 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
463 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
464 |
+
Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
|
465 |
+
this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
|
466 |
+
the complete sequence length.
|
467 |
+
"""
|
468 |
+
|
469 |
+
|
470 |
+
@add_start_docstrings(
|
471 |
+
"The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
|
472 |
+
QWEN2_START_DOCSTRING,
|
473 |
+
)
|
474 |
+
class Qwen2Model(Qwen2PreTrainedModel):
|
475 |
+
"""
|
476 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
|
477 |
+
|
478 |
+
Args:
|
479 |
+
config: Qwen2Config
|
480 |
+
"""
|
481 |
+
|
482 |
+
def __init__(self, config: Qwen2Config):
|
483 |
+
super().__init__(config)
|
484 |
+
self.padding_idx = config.pad_token_id
|
485 |
+
self.vocab_size = config.vocab_size
|
486 |
+
|
487 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
488 |
+
self.layers = nn.ModuleList(
|
489 |
+
[Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
490 |
+
)
|
491 |
+
self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
492 |
+
self.rotary_emb = Qwen2RotaryEmbedding(config=config)
|
493 |
+
self.gradient_checkpointing = False
|
494 |
+
|
495 |
+
# Initialize weights and apply final processing
|
496 |
+
self.post_init()
|
497 |
+
|
498 |
+
def get_input_embeddings(self):
|
499 |
+
return self.embed_tokens
|
500 |
+
|
501 |
+
def set_input_embeddings(self, value):
|
502 |
+
self.embed_tokens = value
|
503 |
+
|
504 |
+
@add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
|
505 |
+
def forward(
|
506 |
+
self,
|
507 |
+
input_ids: torch.LongTensor = None,
|
508 |
+
attention_mask: Optional[torch.Tensor] = None,
|
509 |
+
position_ids: Optional[torch.LongTensor] = None,
|
510 |
+
past_key_values: Optional[Cache] = None,
|
511 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
512 |
+
use_cache: Optional[bool] = None,
|
513 |
+
output_attentions: Optional[bool] = None,
|
514 |
+
output_hidden_states: Optional[bool] = None,
|
515 |
+
return_dict: Optional[bool] = None,
|
516 |
+
cache_position: Optional[torch.LongTensor] = None,
|
517 |
+
**flash_attn_kwargs: Unpack[FlashAttentionKwargs],
|
518 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
519 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
520 |
+
output_hidden_states = (
|
521 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
522 |
+
)
|
523 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
524 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
525 |
+
|
526 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
527 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
528 |
+
|
529 |
+
if self.gradient_checkpointing and self.training and use_cache:
|
530 |
+
logger.warning_once(
|
531 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
|
532 |
+
)
|
533 |
+
use_cache = False
|
534 |
+
|
535 |
+
if inputs_embeds is None:
|
536 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
537 |
+
|
538 |
+
if use_cache and past_key_values is None:
|
539 |
+
past_key_values = DynamicCache()
|
540 |
+
|
541 |
+
if cache_position is None:
|
542 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
543 |
+
cache_position = torch.arange(
|
544 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
545 |
+
)
|
546 |
+
|
547 |
+
if position_ids is None:
|
548 |
+
position_ids = cache_position.unsqueeze(0)
|
549 |
+
|
550 |
+
causal_mask = self._update_causal_mask(
|
551 |
+
attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
|
552 |
+
)
|
553 |
+
|
554 |
+
hidden_states = inputs_embeds
|
555 |
+
|
556 |
+
# create position embeddings to be shared across the decoder layers
|
557 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
558 |
+
|
559 |
+
# decoder layers
|
560 |
+
all_hidden_states = () if output_hidden_states else None
|
561 |
+
all_self_attns = () if output_attentions else None
|
562 |
+
|
563 |
+
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
|
564 |
+
if output_hidden_states:
|
565 |
+
all_hidden_states += (hidden_states,)
|
566 |
+
|
567 |
+
if self.gradient_checkpointing and self.training:
|
568 |
+
layer_outputs = self._gradient_checkpointing_func(
|
569 |
+
decoder_layer.__call__,
|
570 |
+
hidden_states,
|
571 |
+
causal_mask,
|
572 |
+
position_ids,
|
573 |
+
past_key_values,
|
574 |
+
output_attentions,
|
575 |
+
use_cache,
|
576 |
+
cache_position,
|
577 |
+
position_embeddings,
|
578 |
+
)
|
579 |
+
else:
|
580 |
+
layer_outputs = decoder_layer(
|
581 |
+
hidden_states,
|
582 |
+
attention_mask=causal_mask,
|
583 |
+
position_ids=position_ids,
|
584 |
+
past_key_value=past_key_values,
|
585 |
+
output_attentions=output_attentions,
|
586 |
+
use_cache=use_cache,
|
587 |
+
cache_position=cache_position,
|
588 |
+
position_embeddings=position_embeddings,
|
589 |
+
**flash_attn_kwargs,
|
590 |
+
)
|
591 |
+
|
592 |
+
hidden_states = layer_outputs[0]
|
593 |
+
|
594 |
+
if output_attentions:
|
595 |
+
all_self_attns += (layer_outputs[1],)
|
596 |
+
|
597 |
+
hidden_states = self.norm(hidden_states)
|
598 |
+
|
599 |
+
# add hidden states from the last decoder layer
|
600 |
+
if output_hidden_states:
|
601 |
+
all_hidden_states += (hidden_states,)
|
602 |
+
|
603 |
+
output = BaseModelOutputWithPast(
|
604 |
+
last_hidden_state=hidden_states,
|
605 |
+
past_key_values=past_key_values if use_cache else None,
|
606 |
+
hidden_states=all_hidden_states,
|
607 |
+
attentions=all_self_attns,
|
608 |
+
)
|
609 |
+
return output if return_dict else output.to_tuple()
|
610 |
+
|
611 |
+
def _update_causal_mask(
|
612 |
+
self,
|
613 |
+
attention_mask: torch.Tensor,
|
614 |
+
input_tensor: torch.Tensor,
|
615 |
+
cache_position: torch.Tensor,
|
616 |
+
past_key_values: Cache,
|
617 |
+
output_attentions: bool,
|
618 |
+
):
|
619 |
+
if self.config._attn_implementation == "flash_attention_2":
|
620 |
+
if attention_mask is not None and (attention_mask == 0.0).any():
|
621 |
+
return attention_mask
|
622 |
+
return None
|
623 |
+
|
624 |
+
# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
|
625 |
+
# order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
|
626 |
+
# to infer the attention mask.
|
627 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
628 |
+
using_static_cache = isinstance(past_key_values, StaticCache)
|
629 |
+
|
630 |
+
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
|
631 |
+
if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
|
632 |
+
if AttentionMaskConverter._ignore_causal_mask_sdpa(
|
633 |
+
attention_mask,
|
634 |
+
inputs_embeds=input_tensor,
|
635 |
+
past_key_values_length=past_seen_tokens,
|
636 |
+
is_training=self.training,
|
637 |
+
):
|
638 |
+
return None
|
639 |
+
|
640 |
+
dtype, device = input_tensor.dtype, input_tensor.device
|
641 |
+
sequence_length = input_tensor.shape[1]
|
642 |
+
if using_static_cache:
|
643 |
+
target_length = past_key_values.get_max_cache_shape()
|
644 |
+
else:
|
645 |
+
target_length = (
|
646 |
+
attention_mask.shape[-1]
|
647 |
+
if isinstance(attention_mask, torch.Tensor)
|
648 |
+
else past_seen_tokens + sequence_length + 1
|
649 |
+
)
|
650 |
+
|
651 |
+
# In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
|
652 |
+
causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
|
653 |
+
attention_mask,
|
654 |
+
sequence_length=sequence_length,
|
655 |
+
target_length=target_length,
|
656 |
+
dtype=dtype,
|
657 |
+
device=device,
|
658 |
+
cache_position=cache_position,
|
659 |
+
batch_size=input_tensor.shape[0],
|
660 |
+
)
|
661 |
+
|
662 |
+
if (
|
663 |
+
self.config._attn_implementation == "sdpa"
|
664 |
+
and attention_mask is not None
|
665 |
+
and attention_mask.device.type == "cuda"
|
666 |
+
and not output_attentions
|
667 |
+
):
|
668 |
+
# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
|
669 |
+
# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
|
670 |
+
# Details: https://github.com/pytorch/pytorch/issues/110213
|
671 |
+
min_dtype = torch.finfo(dtype).min
|
672 |
+
causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
|
673 |
+
|
674 |
+
return causal_mask
|
675 |
+
|
676 |
+
@staticmethod
|
677 |
+
def _prepare_4d_causal_attention_mask_with_cache_position(
|
678 |
+
attention_mask: torch.Tensor,
|
679 |
+
sequence_length: int,
|
680 |
+
target_length: int,
|
681 |
+
dtype: torch.dtype,
|
682 |
+
device: torch.device,
|
683 |
+
cache_position: torch.Tensor,
|
684 |
+
batch_size: int,
|
685 |
+
**kwargs,
|
686 |
+
):
|
687 |
+
"""
|
688 |
+
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
|
689 |
+
`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
|
690 |
+
|
691 |
+
Args:
|
692 |
+
attention_mask (`torch.Tensor`):
|
693 |
+
A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
|
694 |
+
`(batch_size, 1, query_length, key_value_length)`.
|
695 |
+
sequence_length (`int`):
|
696 |
+
The sequence length being processed.
|
697 |
+
target_length (`int`):
|
698 |
+
The target length: when generating with static cache, the mask should be as long as the static cache,
|
699 |
+
to account for the 0 padding, the part of the cache that is not filled yet.
|
700 |
+
dtype (`torch.dtype`):
|
701 |
+
The dtype to use for the 4D attention mask.
|
702 |
+
device (`torch.device`):
|
703 |
+
The device to plcae the 4D attention mask on.
|
704 |
+
cache_position (`torch.Tensor`):
|
705 |
+
Indices depicting the position of the input sequence tokens in the sequence.
|
706 |
+
batch_size (`torch.Tensor`):
|
707 |
+
Batch size.
|
708 |
+
"""
|
709 |
+
if attention_mask is not None and attention_mask.dim() == 4:
|
710 |
+
# In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
|
711 |
+
causal_mask = attention_mask
|
712 |
+
else:
|
713 |
+
min_dtype = torch.finfo(dtype).min
|
714 |
+
causal_mask = torch.full(
|
715 |
+
(sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
|
716 |
+
)
|
717 |
+
if sequence_length != 1:
|
718 |
+
causal_mask = torch.triu(causal_mask, diagonal=1)
|
719 |
+
causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
|
720 |
+
causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
|
721 |
+
if attention_mask is not None:
|
722 |
+
causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
|
723 |
+
mask_length = attention_mask.shape[-1]
|
724 |
+
padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
|
725 |
+
padding_mask = padding_mask == 0
|
726 |
+
causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
|
727 |
+
padding_mask, min_dtype
|
728 |
+
)
|
729 |
+
|
730 |
+
return causal_mask
|
731 |
+
|
732 |
+
|
733 |
+
class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
|
734 |
+
|
735 |
+
|
736 |
+
class Qwen2ForCausalLM(Qwen2PreTrainedModel, GenerationMixin):
|
737 |
+
_tied_weights_keys = ["lm_head.weight"]
|
738 |
+
_tp_plan = {"lm_head": "colwise_rep"}
|
739 |
+
|
740 |
+
def __init__(self, config):
|
741 |
+
super().__init__(config)
|
742 |
+
self.model = Qwen2Model(config)
|
743 |
+
self.vocab_size = config.vocab_size
|
744 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
745 |
+
|
746 |
+
# Initialize weights and apply final processing
|
747 |
+
self.post_init()
|
748 |
+
|
749 |
+
def get_input_embeddings(self):
|
750 |
+
return self.model.embed_tokens
|
751 |
+
|
752 |
+
def set_input_embeddings(self, value):
|
753 |
+
self.model.embed_tokens = value
|
754 |
+
|
755 |
+
def get_output_embeddings(self):
|
756 |
+
return self.lm_head
|
757 |
+
|
758 |
+
def set_output_embeddings(self, new_embeddings):
|
759 |
+
self.lm_head = new_embeddings
|
760 |
+
|
761 |
+
def set_decoder(self, decoder):
|
762 |
+
self.model = decoder
|
763 |
+
|
764 |
+
def get_decoder(self):
|
765 |
+
return self.model
|
766 |
+
|
767 |
+
@deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
|
768 |
+
@add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
|
769 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
770 |
+
def forward(
|
771 |
+
self,
|
772 |
+
input_ids: torch.LongTensor = None,
|
773 |
+
attention_mask: Optional[torch.Tensor] = None,
|
774 |
+
position_ids: Optional[torch.LongTensor] = None,
|
775 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
776 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
777 |
+
labels: Optional[torch.LongTensor] = None,
|
778 |
+
use_cache: Optional[bool] = None,
|
779 |
+
output_attentions: Optional[bool] = None,
|
780 |
+
output_hidden_states: Optional[bool] = None,
|
781 |
+
return_dict: Optional[bool] = None,
|
782 |
+
cache_position: Optional[torch.LongTensor] = None,
|
783 |
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
784 |
+
**kwargs: Unpack[KwargsForCausalLM],
|
785 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
786 |
+
r"""
|
787 |
+
Args:
|
788 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
789 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
790 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
791 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
792 |
+
|
793 |
+
logits_to_keep (`int` or `torch.Tensor`, *optional*):
|
794 |
+
If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
|
795 |
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
796 |
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
797 |
+
If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
|
798 |
+
This is useful when using packed tensor format (single dimension for batch and sequence length).
|
799 |
+
|
800 |
+
Returns:
|
801 |
+
|
802 |
+
Example:
|
803 |
+
|
804 |
+
```python
|
805 |
+
>>> from transformers import AutoTokenizer, Qwen2ForCausalLM
|
806 |
+
|
807 |
+
>>> model = Qwen2ForCausalLM.from_pretrained("meta-qwen2/Qwen2-2-7b-hf")
|
808 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("meta-qwen2/Qwen2-2-7b-hf")
|
809 |
+
|
810 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
811 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
812 |
+
|
813 |
+
>>> # Generate
|
814 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
815 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
816 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
817 |
+
```"""
|
818 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
819 |
+
output_hidden_states = (
|
820 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
821 |
+
)
|
822 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
823 |
+
|
824 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
825 |
+
outputs = self.model(
|
826 |
+
input_ids=input_ids,
|
827 |
+
attention_mask=attention_mask,
|
828 |
+
position_ids=position_ids,
|
829 |
+
past_key_values=past_key_values,
|
830 |
+
inputs_embeds=inputs_embeds,
|
831 |
+
use_cache=use_cache,
|
832 |
+
output_attentions=output_attentions,
|
833 |
+
output_hidden_states=output_hidden_states,
|
834 |
+
return_dict=return_dict,
|
835 |
+
cache_position=cache_position,
|
836 |
+
**kwargs,
|
837 |
+
)
|
838 |
+
|
839 |
+
hidden_states = outputs[0]
|
840 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
841 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
842 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
843 |
+
|
844 |
+
loss = None
|
845 |
+
if labels is not None:
|
846 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
847 |
+
|
848 |
+
if not return_dict:
|
849 |
+
output = (logits,) + outputs[1:]
|
850 |
+
return (loss,) + output if loss is not None else output
|
851 |
+
|
852 |
+
return CausalLMOutputWithPast(
|
853 |
+
loss=loss,
|
854 |
+
logits=logits,
|
855 |
+
past_key_values=outputs.past_key_values,
|
856 |
+
hidden_states=outputs.hidden_states,
|
857 |
+
attentions=outputs.attentions,
|
858 |
+
)
|
859 |
+
|
860 |
+
|
861 |
+
@add_start_docstrings(
|
862 |
+
"""
|
863 |
+
The Qwen2 Model transformer with a sequence classification head on top (linear layer).
|
864 |
+
|
865 |
+
[`Qwen2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
866 |
+
(e.g. GPT-2) do.
|
867 |
+
|
868 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
869 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
870 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
871 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
872 |
+
each row of the batch).
|
873 |
+
""",
|
874 |
+
QWEN2_START_DOCSTRING,
|
875 |
+
)
|
876 |
+
class Qwen2ForSequenceClassification(Qwen2PreTrainedModel):
|
877 |
+
def __init__(self, config):
|
878 |
+
super().__init__(config)
|
879 |
+
self.num_labels = config.num_labels
|
880 |
+
self.model = Qwen2Model(config)
|
881 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
882 |
+
|
883 |
+
# Initialize weights and apply final processing
|
884 |
+
self.post_init()
|
885 |
+
|
886 |
+
def get_input_embeddings(self):
|
887 |
+
return self.model.embed_tokens
|
888 |
+
|
889 |
+
def set_input_embeddings(self, value):
|
890 |
+
self.model.embed_tokens = value
|
891 |
+
|
892 |
+
@add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
|
893 |
+
def forward(
|
894 |
+
self,
|
895 |
+
input_ids: Optional[torch.LongTensor] = None,
|
896 |
+
attention_mask: Optional[torch.Tensor] = None,
|
897 |
+
position_ids: Optional[torch.LongTensor] = None,
|
898 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
899 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
900 |
+
labels: Optional[torch.LongTensor] = None,
|
901 |
+
use_cache: Optional[bool] = None,
|
902 |
+
output_attentions: Optional[bool] = None,
|
903 |
+
output_hidden_states: Optional[bool] = None,
|
904 |
+
return_dict: Optional[bool] = None,
|
905 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
906 |
+
r"""
|
907 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
908 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
909 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
910 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
911 |
+
"""
|
912 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
913 |
+
|
914 |
+
transformer_outputs = self.model(
|
915 |
+
input_ids,
|
916 |
+
attention_mask=attention_mask,
|
917 |
+
position_ids=position_ids,
|
918 |
+
past_key_values=past_key_values,
|
919 |
+
inputs_embeds=inputs_embeds,
|
920 |
+
use_cache=use_cache,
|
921 |
+
output_attentions=output_attentions,
|
922 |
+
output_hidden_states=output_hidden_states,
|
923 |
+
return_dict=return_dict,
|
924 |
+
)
|
925 |
+
hidden_states = transformer_outputs[0]
|
926 |
+
logits = self.score(hidden_states)
|
927 |
+
|
928 |
+
if input_ids is not None:
|
929 |
+
batch_size = input_ids.shape[0]
|
930 |
+
else:
|
931 |
+
batch_size = inputs_embeds.shape[0]
|
932 |
+
|
933 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
934 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
935 |
+
if self.config.pad_token_id is None:
|
936 |
+
sequence_lengths = -1
|
937 |
+
else:
|
938 |
+
if input_ids is not None:
|
939 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
940 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
941 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
942 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
943 |
+
else:
|
944 |
+
sequence_lengths = -1
|
945 |
+
|
946 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
947 |
+
|
948 |
+
loss = None
|
949 |
+
if labels is not None:
|
950 |
+
loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
|
951 |
+
|
952 |
+
if not return_dict:
|
953 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
954 |
+
return ((loss,) + output) if loss is not None else output
|
955 |
+
|
956 |
+
return SequenceClassifierOutputWithPast(
|
957 |
+
loss=loss,
|
958 |
+
logits=pooled_logits,
|
959 |
+
past_key_values=transformer_outputs.past_key_values,
|
960 |
+
hidden_states=transformer_outputs.hidden_states,
|
961 |
+
attentions=transformer_outputs.attentions,
|
962 |
+
)
|
963 |
+
|
964 |
+
|
965 |
+
@add_start_docstrings(
|
966 |
+
"""
|
967 |
+
The Qwen2 Model transformer with a token classification head on top (a linear layer on top of the hidden-states
|
968 |
+
output) e.g. for Named-Entity-Recognition (NER) tasks.
|
969 |
+
""",
|
970 |
+
QWEN2_START_DOCSTRING,
|
971 |
+
)
|
972 |
+
class Qwen2ForTokenClassification(Qwen2PreTrainedModel):
|
973 |
+
def __init__(self, config):
|
974 |
+
super().__init__(config)
|
975 |
+
self.num_labels = config.num_labels
|
976 |
+
self.model = Qwen2Model(config)
|
977 |
+
if getattr(config, "classifier_dropout", None) is not None:
|
978 |
+
classifier_dropout = config.classifier_dropout
|
979 |
+
elif getattr(config, "hidden_dropout", None) is not None:
|
980 |
+
classifier_dropout = config.hidden_dropout
|
981 |
+
else:
|
982 |
+
classifier_dropout = 0.1
|
983 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
984 |
+
self.score = nn.Linear(config.hidden_size, config.num_labels)
|
985 |
+
|
986 |
+
# Initialize weights and apply final processing
|
987 |
+
self.post_init()
|
988 |
+
|
989 |
+
def get_input_embeddings(self):
|
990 |
+
return self.model.embed_tokens
|
991 |
+
|
992 |
+
def set_input_embeddings(self, value):
|
993 |
+
self.model.embed_tokens = value
|
994 |
+
|
995 |
+
@add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
|
996 |
+
@add_code_sample_docstrings(
|
997 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
998 |
+
output_type=TokenClassifierOutput,
|
999 |
+
config_class=_CONFIG_FOR_DOC,
|
1000 |
+
)
|
1001 |
+
def forward(
|
1002 |
+
self,
|
1003 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1004 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1005 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1006 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1007 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1008 |
+
labels: Optional[torch.LongTensor] = None,
|
1009 |
+
use_cache: Optional[bool] = None,
|
1010 |
+
output_attentions: Optional[bool] = None,
|
1011 |
+
output_hidden_states: Optional[bool] = None,
|
1012 |
+
return_dict: Optional[bool] = None,
|
1013 |
+
) -> Union[Tuple, TokenClassifierOutput]:
|
1014 |
+
r"""
|
1015 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1016 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1017 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1018 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1019 |
+
"""
|
1020 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1021 |
+
|
1022 |
+
outputs = self.model(
|
1023 |
+
input_ids,
|
1024 |
+
attention_mask=attention_mask,
|
1025 |
+
position_ids=position_ids,
|
1026 |
+
past_key_values=past_key_values,
|
1027 |
+
inputs_embeds=inputs_embeds,
|
1028 |
+
use_cache=use_cache,
|
1029 |
+
output_attentions=output_attentions,
|
1030 |
+
output_hidden_states=output_hidden_states,
|
1031 |
+
return_dict=return_dict,
|
1032 |
+
)
|
1033 |
+
sequence_output = outputs[0]
|
1034 |
+
sequence_output = self.dropout(sequence_output)
|
1035 |
+
logits = self.score(sequence_output)
|
1036 |
+
|
1037 |
+
loss = None
|
1038 |
+
if labels is not None:
|
1039 |
+
loss = self.loss_function(logits, labels, self.config)
|
1040 |
+
|
1041 |
+
if not return_dict:
|
1042 |
+
output = (logits,) + outputs[2:]
|
1043 |
+
return ((loss,) + output) if loss is not None else output
|
1044 |
+
|
1045 |
+
return TokenClassifierOutput(
|
1046 |
+
loss=loss,
|
1047 |
+
logits=logits,
|
1048 |
+
hidden_states=outputs.hidden_states,
|
1049 |
+
attentions=outputs.attentions,
|
1050 |
+
)
|
1051 |
+
|
1052 |
+
|
1053 |
+
@add_start_docstrings(
|
1054 |
+
"""
|
1055 |
+
The Qwen2 Model transformer with a span classification head on top for extractive question-answering tasks like
|
1056 |
+
SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
1057 |
+
""",
|
1058 |
+
QWEN2_START_DOCSTRING,
|
1059 |
+
)
|
1060 |
+
class Qwen2ForQuestionAnswering(Qwen2PreTrainedModel):
|
1061 |
+
base_model_prefix = "transformer"
|
1062 |
+
|
1063 |
+
def __init__(self, config):
|
1064 |
+
super().__init__(config)
|
1065 |
+
self.transformer = Qwen2Model(config)
|
1066 |
+
self.qa_outputs = nn.Linear(config.hidden_size, 2)
|
1067 |
+
|
1068 |
+
# Initialize weights and apply final processing
|
1069 |
+
self.post_init()
|
1070 |
+
|
1071 |
+
def get_input_embeddings(self):
|
1072 |
+
return self.transformer.embed_tokens
|
1073 |
+
|
1074 |
+
def set_input_embeddings(self, value):
|
1075 |
+
self.transformer.embed_tokens = value
|
1076 |
+
|
1077 |
+
@add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
|
1078 |
+
def forward(
|
1079 |
+
self,
|
1080 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1081 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
1082 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1083 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
1084 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1085 |
+
start_positions: Optional[torch.LongTensor] = None,
|
1086 |
+
end_positions: Optional[torch.LongTensor] = None,
|
1087 |
+
output_attentions: Optional[bool] = None,
|
1088 |
+
output_hidden_states: Optional[bool] = None,
|
1089 |
+
return_dict: Optional[bool] = None,
|
1090 |
+
**kwargs,
|
1091 |
+
) -> Union[Tuple, QuestionAnsweringModelOutput]:
|
1092 |
+
r"""
|
1093 |
+
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1094 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
1095 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
1096 |
+
are not taken into account for computing the loss.
|
1097 |
+
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1098 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
1099 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
1100 |
+
are not taken into account for computing the loss.
|
1101 |
+
"""
|
1102 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1103 |
+
|
1104 |
+
outputs = self.transformer(
|
1105 |
+
input_ids,
|
1106 |
+
attention_mask=attention_mask,
|
1107 |
+
position_ids=position_ids,
|
1108 |
+
past_key_values=past_key_values,
|
1109 |
+
inputs_embeds=inputs_embeds,
|
1110 |
+
output_attentions=output_attentions,
|
1111 |
+
output_hidden_states=output_hidden_states,
|
1112 |
+
return_dict=return_dict,
|
1113 |
+
)
|
1114 |
+
|
1115 |
+
sequence_output = outputs[0]
|
1116 |
+
|
1117 |
+
logits = self.qa_outputs(sequence_output)
|
1118 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
1119 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
1120 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
1121 |
+
|
1122 |
+
loss = None
|
1123 |
+
if start_positions is not None and end_positions is not None:
|
1124 |
+
loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
|
1125 |
+
|
1126 |
+
if not return_dict:
|
1127 |
+
output = (start_logits, end_logits) + outputs[2:]
|
1128 |
+
return ((loss,) + output) if loss is not None else output
|
1129 |
+
|
1130 |
+
return QuestionAnsweringModelOutput(
|
1131 |
+
loss=loss,
|
1132 |
+
start_logits=start_logits,
|
1133 |
+
end_logits=end_logits,
|
1134 |
+
hidden_states=outputs.hidden_states,
|
1135 |
+
attentions=outputs.attentions,
|
1136 |
+
)
|
Qwen2.5-3B-512k-mi-flexpf_090-39iters-2025041801/pytorch_model.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:3d09b2db6c61d7fcfb6138dfb03ec8d6796b7a08450713e6538faddf6063f935
|
3 |
+
size 6172019146
|
Qwen2.5-3B-512k-mi-flexpf_090-39iters-2025041801/tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
Qwen2.5-3B-512k-mi-flexpf_090-39iters-2025041801/tokenizer_config.json
ADDED
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"add_bos_token": false,
|
3 |
+
"add_prefix_space": false,
|
4 |
+
"added_tokens_decoder": {
|
5 |
+
"151643": {
|
6 |
+
"content": "<|endoftext|>",
|
7 |
+
"lstrip": false,
|
8 |
+
"normalized": false,
|
9 |
+
"rstrip": false,
|
10 |
+
"single_word": false,
|
11 |
+
"special": true
|
12 |
+
},
|
13 |
+
"151644": {
|
14 |
+
"content": "<|im_start|>",
|
15 |
+
"lstrip": false,
|
16 |
+
"normalized": false,
|
17 |
+
"rstrip": false,
|
18 |
+
"single_word": false,
|
19 |
+
"special": true
|
20 |
+
},
|
21 |
+
"151645": {
|
22 |
+
"content": "<|im_end|>",
|
23 |
+
"lstrip": false,
|
24 |
+
"normalized": false,
|
25 |
+
"rstrip": false,
|
26 |
+
"single_word": false,
|
27 |
+
"special": true
|
28 |
+
},
|
29 |
+
"151646": {
|
30 |
+
"content": "<|object_ref_start|>",
|
31 |
+
"lstrip": false,
|
32 |
+
"normalized": false,
|
33 |
+
"rstrip": false,
|
34 |
+
"single_word": false,
|
35 |
+
"special": true
|
36 |
+
},
|
37 |
+
"151647": {
|
38 |
+
"content": "<|object_ref_end|>",
|
39 |
+
"lstrip": false,
|
40 |
+
"normalized": false,
|
41 |
+
"rstrip": false,
|
42 |
+
"single_word": false,
|
43 |
+
"special": true
|
44 |
+
},
|
45 |
+
"151648": {
|
46 |
+
"content": "<|box_start|>",
|
47 |
+
"lstrip": false,
|
48 |
+
"normalized": false,
|
49 |
+
"rstrip": false,
|
50 |
+
"single_word": false,
|
51 |
+
"special": true
|
52 |
+
},
|
53 |
+
"151649": {
|
54 |
+
"content": "<|box_end|>",
|
55 |
+
"lstrip": false,
|
56 |
+
"normalized": false,
|
57 |
+
"rstrip": false,
|
58 |
+
"single_word": false,
|
59 |
+
"special": true
|
60 |
+
},
|
61 |
+
"151650": {
|
62 |
+
"content": "<|quad_start|>",
|
63 |
+
"lstrip": false,
|
64 |
+
"normalized": false,
|
65 |
+
"rstrip": false,
|
66 |
+
"single_word": false,
|
67 |
+
"special": true
|
68 |
+
},
|
69 |
+
"151651": {
|
70 |
+
"content": "<|quad_end|>",
|
71 |
+
"lstrip": false,
|
72 |
+
"normalized": false,
|
73 |
+
"rstrip": false,
|
74 |
+
"single_word": false,
|
75 |
+
"special": true
|
76 |
+
},
|
77 |
+
"151652": {
|
78 |
+
"content": "<|vision_start|>",
|
79 |
+
"lstrip": false,
|
80 |
+
"normalized": false,
|
81 |
+
"rstrip": false,
|
82 |
+
"single_word": false,
|
83 |
+
"special": true
|
84 |
+
},
|
85 |
+
"151653": {
|
86 |
+
"content": "<|vision_end|>",
|
87 |
+
"lstrip": false,
|
88 |
+
"normalized": false,
|
89 |
+
"rstrip": false,
|
90 |
+
"single_word": false,
|
91 |
+
"special": true
|
92 |
+
},
|
93 |
+
"151654": {
|
94 |
+
"content": "<|vision_pad|>",
|
95 |
+
"lstrip": false,
|
96 |
+
"normalized": false,
|
97 |
+
"rstrip": false,
|
98 |
+
"single_word": false,
|
99 |
+
"special": true
|
100 |
+
},
|
101 |
+
"151655": {
|
102 |
+
"content": "<|image_pad|>",
|
103 |
+
"lstrip": false,
|
104 |
+
"normalized": false,
|
105 |
+
"rstrip": false,
|
106 |
+
"single_word": false,
|
107 |
+
"special": true
|
108 |
+
},
|
109 |
+
"151656": {
|
110 |
+
"content": "<|video_pad|>",
|
111 |
+
"lstrip": false,
|
112 |
+
"normalized": false,
|
113 |
+
"rstrip": false,
|
114 |
+
"single_word": false,
|
115 |
+
"special": true
|
116 |
+
},
|
117 |
+
"151657": {
|
118 |
+
"content": "<tool_call>",
|
119 |
+
"lstrip": false,
|
120 |
+
"normalized": false,
|
121 |
+
"rstrip": false,
|
122 |
+
"single_word": false,
|
123 |
+
"special": false
|
124 |
+
},
|
125 |
+
"151658": {
|
126 |
+
"content": "</tool_call>",
|
127 |
+
"lstrip": false,
|
128 |
+
"normalized": false,
|
129 |
+
"rstrip": false,
|
130 |
+
"single_word": false,
|
131 |
+
"special": false
|
132 |
+
},
|
133 |
+
"151659": {
|
134 |
+
"content": "<|fim_prefix|>",
|
135 |
+
"lstrip": false,
|
136 |
+
"normalized": false,
|
137 |
+
"rstrip": false,
|
138 |
+
"single_word": false,
|
139 |
+
"special": false
|
140 |
+
},
|
141 |
+
"151660": {
|
142 |
+
"content": "<|fim_middle|>",
|
143 |
+
"lstrip": false,
|
144 |
+
"normalized": false,
|
145 |
+
"rstrip": false,
|
146 |
+
"single_word": false,
|
147 |
+
"special": false
|
148 |
+
},
|
149 |
+
"151661": {
|
150 |
+
"content": "<|fim_suffix|>",
|
151 |
+
"lstrip": false,
|
152 |
+
"normalized": false,
|
153 |
+
"rstrip": false,
|
154 |
+
"single_word": false,
|
155 |
+
"special": false
|
156 |
+
},
|
157 |
+
"151662": {
|
158 |
+
"content": "<|fim_pad|>",
|
159 |
+
"lstrip": false,
|
160 |
+
"normalized": false,
|
161 |
+
"rstrip": false,
|
162 |
+
"single_word": false,
|
163 |
+
"special": false
|
164 |
+
},
|
165 |
+
"151663": {
|
166 |
+
"content": "<|repo_name|>",
|
167 |
+
"lstrip": false,
|
168 |
+
"normalized": false,
|
169 |
+
"rstrip": false,
|
170 |
+
"single_word": false,
|
171 |
+
"special": false
|
172 |
+
},
|
173 |
+
"151664": {
|
174 |
+
"content": "<|file_sep|>",
|
175 |
+
"lstrip": false,
|
176 |
+
"normalized": false,
|
177 |
+
"rstrip": false,
|
178 |
+
"single_word": false,
|
179 |
+
"special": false
|
180 |
+
}
|
181 |
+
},
|
182 |
+
"additional_special_tokens": [
|
183 |
+
"<|im_start|>",
|
184 |
+
"<|im_end|>",
|
185 |
+
"<|object_ref_start|>",
|
186 |
+
"<|object_ref_end|>",
|
187 |
+
"<|box_start|>",
|
188 |
+
"<|box_end|>",
|
189 |
+
"<|quad_start|>",
|
190 |
+
"<|quad_end|>",
|
191 |
+
"<|vision_start|>",
|
192 |
+
"<|vision_end|>",
|
193 |
+
"<|vision_pad|>",
|
194 |
+
"<|image_pad|>",
|
195 |
+
"<|video_pad|>"
|
196 |
+
],
|
197 |
+
"bos_token": null,
|
198 |
+
"chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0]['role'] == 'system' %}\n {{- messages[0]['content'] }}\n {%- else %}\n {{- 'You are a helpful assistant.' }}\n {%- endif %}\n {{- \"\\n\\n# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n {%- if messages[0]['role'] == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0]['content'] + '<|im_end|>\\n' }}\n {%- else %}\n {{- '<|im_start|>system\\nYou are a helpful assistant.<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- for message in messages %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) or (message.role == \"assistant\" and not message.tool_calls) %}\n {{- '<|im_start|>' + message.role + '\\n' + message.content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {{- '<|im_start|>' + message.role }}\n {%- if message.content %}\n {{- '\\n' + message.content }}\n {%- endif %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '\\n<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {{- tool_call.arguments | tojson }}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- message.content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n{%- endif %}\n",
|
199 |
+
"clean_up_tokenization_spaces": false,
|
200 |
+
"eos_token": "<|endoftext|>",
|
201 |
+
"errors": "replace",
|
202 |
+
"model_max_length": 524288,
|
203 |
+
"pad_token": "<|endoftext|>",
|
204 |
+
"split_special_tokens": false,
|
205 |
+
"tokenizer_class": "Qwen2Tokenizer",
|
206 |
+
"unk_token": null
|
207 |
+
}
|
Qwen2.5-3B-512k-mi-flexpf_090-39iters-2025041801/vocab.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|