End of training
Browse files- README.md +59 -0
- config.json +69 -0
- generation_config.json +6 -0
- model-00001-of-00003.safetensors +3 -0
- model-00002-of-00003.safetensors +3 -0
- model-00003-of-00003.safetensors +3 -0
- model.safetensors.index.json +298 -0
- sparsification_sftt.py +1509 -0
README.md
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
license: apache-2.0
|
3 |
+
base_model: mistralai/Mistral-7B-v0.1
|
4 |
+
tags:
|
5 |
+
- generated_from_trainer
|
6 |
+
model-index:
|
7 |
+
- name: Mistral_Sparse_refined_web_90p_2024-03-20
|
8 |
+
results: []
|
9 |
+
---
|
10 |
+
|
11 |
+
<!-- This model card has been generated automatically according to the information the Trainer had access to. You
|
12 |
+
should probably proofread and complete it, then remove this comment. -->
|
13 |
+
|
14 |
+
# Mistral_Sparse_refined_web_90p_2024-03-20
|
15 |
+
|
16 |
+
This model is a fine-tuned version of [mistralai/Mistral-7B-v0.1](https://huggingface.co/mistralai/Mistral-7B-v0.1) on the None dataset.
|
17 |
+
It achieves the following results on the evaluation set:
|
18 |
+
- Loss: 7.5087
|
19 |
+
|
20 |
+
## Model description
|
21 |
+
|
22 |
+
More information needed
|
23 |
+
|
24 |
+
## Intended uses & limitations
|
25 |
+
|
26 |
+
More information needed
|
27 |
+
|
28 |
+
## Training and evaluation data
|
29 |
+
|
30 |
+
More information needed
|
31 |
+
|
32 |
+
## Training procedure
|
33 |
+
|
34 |
+
### Training hyperparameters
|
35 |
+
|
36 |
+
The following hyperparameters were used during training:
|
37 |
+
- learning_rate: 1e-05
|
38 |
+
- train_batch_size: 1
|
39 |
+
- eval_batch_size: 1
|
40 |
+
- seed: 0
|
41 |
+
- distributed_type: multi-GPU
|
42 |
+
- num_devices: 4
|
43 |
+
- gradient_accumulation_steps: 4
|
44 |
+
- total_train_batch_size: 16
|
45 |
+
- total_eval_batch_size: 4
|
46 |
+
- optimizer: Adam with betas=(0.9,0.999) and epsilon=1e-08
|
47 |
+
- lr_scheduler_type: linear
|
48 |
+
- training_steps: 1
|
49 |
+
|
50 |
+
### Training results
|
51 |
+
|
52 |
+
|
53 |
+
|
54 |
+
### Framework versions
|
55 |
+
|
56 |
+
- Transformers 4.36.2
|
57 |
+
- Pytorch 2.1.2+cu121
|
58 |
+
- Datasets 2.15.0
|
59 |
+
- Tokenizers 0.15.0
|
config.json
ADDED
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "mistralai/Mistral-7B-v0.1",
|
3 |
+
"architectures": [
|
4 |
+
"SparseMistralforCausalLM"
|
5 |
+
],
|
6 |
+
"attention_dropout": 0.0,
|
7 |
+
"auto_map": {
|
8 |
+
"AutoConfig": "sparsification_sftt.SparseMistralConfig",
|
9 |
+
"AutoModelForCausalLM": "sparsification_sftt.SparseMistralforCausalLM"
|
10 |
+
},
|
11 |
+
"bos_token_id": 1,
|
12 |
+
"eos_token_id": 2,
|
13 |
+
"hidden_act": "silu",
|
14 |
+
"hidden_size": 4096,
|
15 |
+
"initializer_range": 0.02,
|
16 |
+
"intermediate_size": 14336,
|
17 |
+
"max_position_embeddings": 32768,
|
18 |
+
"model_type": "sparse_mistral",
|
19 |
+
"num_attention_heads": 32,
|
20 |
+
"num_hidden_layers": 32,
|
21 |
+
"num_key_value_heads": 8,
|
22 |
+
"rms_norm_eps": 1e-05,
|
23 |
+
"rope_theta": 10000.0,
|
24 |
+
"sliding_window": 4096,
|
25 |
+
"thresholds": [
|
26 |
+
0.049147434532642365,
|
27 |
+
0.06519558280706406,
|
28 |
+
0.13340020179748535,
|
29 |
+
0.12738214433193207,
|
30 |
+
0.14944833517074585,
|
31 |
+
0.15947842597961426,
|
32 |
+
0.16950851678848267,
|
33 |
+
0.17552657425403595,
|
34 |
+
0.18154463171958923,
|
35 |
+
0.1835506409406662,
|
36 |
+
0.19558675587177277,
|
37 |
+
0.20561684668064117,
|
38 |
+
0.2096288800239563,
|
39 |
+
0.21163490414619446,
|
40 |
+
0.225677028298378,
|
41 |
+
0.24172517657279968,
|
42 |
+
0.2577733099460602,
|
43 |
+
0.2678034007549286,
|
44 |
+
0.2718154489994049,
|
45 |
+
0.27382147312164307,
|
46 |
+
0.27582746744155884,
|
47 |
+
0.27582746744155884,
|
48 |
+
0.27582746744155884,
|
49 |
+
0.27582746744155884,
|
50 |
+
0.27582746744155884,
|
51 |
+
0.27582746744155884,
|
52 |
+
0.277833491563797,
|
53 |
+
0.277833491563797,
|
54 |
+
0.35406216979026794,
|
55 |
+
0.5305917859077454,
|
56 |
+
0.8776329159736633,
|
57 |
+
1.0
|
58 |
+
],
|
59 |
+
"tie_word_embeddings": false,
|
60 |
+
"torch_dtype": "bfloat16",
|
61 |
+
"transformers_version": "4.36.2",
|
62 |
+
"use_cache": false,
|
63 |
+
"use_relu": false,
|
64 |
+
"use_resilu": false,
|
65 |
+
"use_sparse_model": true,
|
66 |
+
"use_sparse_predictor": false,
|
67 |
+
"use_sparse_regularization": false,
|
68 |
+
"vocab_size": 32000
|
69 |
+
}
|
generation_config.json
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"bos_token_id": 1,
|
4 |
+
"eos_token_id": 2,
|
5 |
+
"transformers_version": "4.36.2"
|
6 |
+
}
|
model-00001-of-00003.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:facdb5fb934faf94fd03e8d85846592067e471f76a4db39f99e7ee3c94d1375a
|
3 |
+
size 4943162336
|
model-00002-of-00003.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:30c97e4d28b1d6af8ea9cfab3442bf2ccd854580f8be81b7219e47723e12a8f6
|
3 |
+
size 4999819336
|
model-00003-of-00003.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:8347e674a7286cee0c9c29c93e03b67c499a14434a7ec59d7bab11cdeadfb38c
|
3 |
+
size 4540516344
|
model.safetensors.index.json
ADDED
@@ -0,0 +1,298 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"metadata": {
|
3 |
+
"total_size": 14483464192
|
4 |
+
},
|
5 |
+
"weight_map": {
|
6 |
+
"lm_head.weight": "model-00003-of-00003.safetensors",
|
7 |
+
"model.embed_tokens.weight": "model-00001-of-00003.safetensors",
|
8 |
+
"model.layers.0.input_layernorm.weight": "model-00001-of-00003.safetensors",
|
9 |
+
"model.layers.0.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
|
10 |
+
"model.layers.0.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
|
11 |
+
"model.layers.0.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
|
12 |
+
"model.layers.0.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
|
13 |
+
"model.layers.0.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
|
14 |
+
"model.layers.0.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
|
15 |
+
"model.layers.0.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
|
16 |
+
"model.layers.0.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
|
17 |
+
"model.layers.1.input_layernorm.weight": "model-00001-of-00003.safetensors",
|
18 |
+
"model.layers.1.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
|
19 |
+
"model.layers.1.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
|
20 |
+
"model.layers.1.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
|
21 |
+
"model.layers.1.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
|
22 |
+
"model.layers.1.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
|
23 |
+
"model.layers.1.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
|
24 |
+
"model.layers.1.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
|
25 |
+
"model.layers.1.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
|
26 |
+
"model.layers.10.input_layernorm.weight": "model-00002-of-00003.safetensors",
|
27 |
+
"model.layers.10.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
|
28 |
+
"model.layers.10.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
|
29 |
+
"model.layers.10.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
|
30 |
+
"model.layers.10.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
|
31 |
+
"model.layers.10.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
|
32 |
+
"model.layers.10.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
|
33 |
+
"model.layers.10.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
|
34 |
+
"model.layers.10.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
|
35 |
+
"model.layers.11.input_layernorm.weight": "model-00002-of-00003.safetensors",
|
36 |
+
"model.layers.11.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
|
37 |
+
"model.layers.11.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
|
38 |
+
"model.layers.11.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
|
39 |
+
"model.layers.11.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
|
40 |
+
"model.layers.11.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
|
41 |
+
"model.layers.11.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
|
42 |
+
"model.layers.11.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
|
43 |
+
"model.layers.11.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
|
44 |
+
"model.layers.12.input_layernorm.weight": "model-00002-of-00003.safetensors",
|
45 |
+
"model.layers.12.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
|
46 |
+
"model.layers.12.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
|
47 |
+
"model.layers.12.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
|
48 |
+
"model.layers.12.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
|
49 |
+
"model.layers.12.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
|
50 |
+
"model.layers.12.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
|
51 |
+
"model.layers.12.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
|
52 |
+
"model.layers.12.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
|
53 |
+
"model.layers.13.input_layernorm.weight": "model-00002-of-00003.safetensors",
|
54 |
+
"model.layers.13.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
|
55 |
+
"model.layers.13.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
|
56 |
+
"model.layers.13.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
|
57 |
+
"model.layers.13.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
|
58 |
+
"model.layers.13.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
|
59 |
+
"model.layers.13.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
|
60 |
+
"model.layers.13.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
|
61 |
+
"model.layers.13.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
|
62 |
+
"model.layers.14.input_layernorm.weight": "model-00002-of-00003.safetensors",
|
63 |
+
"model.layers.14.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
|
64 |
+
"model.layers.14.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
|
65 |
+
"model.layers.14.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
|
66 |
+
"model.layers.14.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
|
67 |
+
"model.layers.14.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
|
68 |
+
"model.layers.14.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
|
69 |
+
"model.layers.14.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
|
70 |
+
"model.layers.14.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
|
71 |
+
"model.layers.15.input_layernorm.weight": "model-00002-of-00003.safetensors",
|
72 |
+
"model.layers.15.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
|
73 |
+
"model.layers.15.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
|
74 |
+
"model.layers.15.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
|
75 |
+
"model.layers.15.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
|
76 |
+
"model.layers.15.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
|
77 |
+
"model.layers.15.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
|
78 |
+
"model.layers.15.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
|
79 |
+
"model.layers.15.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
|
80 |
+
"model.layers.16.input_layernorm.weight": "model-00002-of-00003.safetensors",
|
81 |
+
"model.layers.16.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
|
82 |
+
"model.layers.16.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
|
83 |
+
"model.layers.16.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
|
84 |
+
"model.layers.16.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
|
85 |
+
"model.layers.16.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
|
86 |
+
"model.layers.16.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
|
87 |
+
"model.layers.16.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
|
88 |
+
"model.layers.16.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
|
89 |
+
"model.layers.17.input_layernorm.weight": "model-00002-of-00003.safetensors",
|
90 |
+
"model.layers.17.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
|
91 |
+
"model.layers.17.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
|
92 |
+
"model.layers.17.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
|
93 |
+
"model.layers.17.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
|
94 |
+
"model.layers.17.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
|
95 |
+
"model.layers.17.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
|
96 |
+
"model.layers.17.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
|
97 |
+
"model.layers.17.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
|
98 |
+
"model.layers.18.input_layernorm.weight": "model-00002-of-00003.safetensors",
|
99 |
+
"model.layers.18.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
|
100 |
+
"model.layers.18.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
|
101 |
+
"model.layers.18.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
|
102 |
+
"model.layers.18.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
|
103 |
+
"model.layers.18.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
|
104 |
+
"model.layers.18.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
|
105 |
+
"model.layers.18.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
|
106 |
+
"model.layers.18.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
|
107 |
+
"model.layers.19.input_layernorm.weight": "model-00002-of-00003.safetensors",
|
108 |
+
"model.layers.19.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
|
109 |
+
"model.layers.19.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
|
110 |
+
"model.layers.19.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
|
111 |
+
"model.layers.19.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
|
112 |
+
"model.layers.19.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
|
113 |
+
"model.layers.19.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
|
114 |
+
"model.layers.19.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
|
115 |
+
"model.layers.19.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
|
116 |
+
"model.layers.2.input_layernorm.weight": "model-00001-of-00003.safetensors",
|
117 |
+
"model.layers.2.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
|
118 |
+
"model.layers.2.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
|
119 |
+
"model.layers.2.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
|
120 |
+
"model.layers.2.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
|
121 |
+
"model.layers.2.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
|
122 |
+
"model.layers.2.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
|
123 |
+
"model.layers.2.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
|
124 |
+
"model.layers.2.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
|
125 |
+
"model.layers.20.input_layernorm.weight": "model-00002-of-00003.safetensors",
|
126 |
+
"model.layers.20.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
|
127 |
+
"model.layers.20.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
|
128 |
+
"model.layers.20.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
|
129 |
+
"model.layers.20.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
|
130 |
+
"model.layers.20.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
|
131 |
+
"model.layers.20.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
|
132 |
+
"model.layers.20.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
|
133 |
+
"model.layers.20.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
|
134 |
+
"model.layers.21.input_layernorm.weight": "model-00002-of-00003.safetensors",
|
135 |
+
"model.layers.21.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
|
136 |
+
"model.layers.21.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
|
137 |
+
"model.layers.21.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
|
138 |
+
"model.layers.21.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
|
139 |
+
"model.layers.21.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
|
140 |
+
"model.layers.21.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
|
141 |
+
"model.layers.21.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
|
142 |
+
"model.layers.21.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
|
143 |
+
"model.layers.22.input_layernorm.weight": "model-00003-of-00003.safetensors",
|
144 |
+
"model.layers.22.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
|
145 |
+
"model.layers.22.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
|
146 |
+
"model.layers.22.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
|
147 |
+
"model.layers.22.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
|
148 |
+
"model.layers.22.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
|
149 |
+
"model.layers.22.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
|
150 |
+
"model.layers.22.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
|
151 |
+
"model.layers.22.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
|
152 |
+
"model.layers.23.input_layernorm.weight": "model-00003-of-00003.safetensors",
|
153 |
+
"model.layers.23.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
|
154 |
+
"model.layers.23.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
|
155 |
+
"model.layers.23.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
|
156 |
+
"model.layers.23.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
|
157 |
+
"model.layers.23.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
|
158 |
+
"model.layers.23.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
|
159 |
+
"model.layers.23.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
|
160 |
+
"model.layers.23.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
|
161 |
+
"model.layers.24.input_layernorm.weight": "model-00003-of-00003.safetensors",
|
162 |
+
"model.layers.24.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
|
163 |
+
"model.layers.24.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
|
164 |
+
"model.layers.24.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
|
165 |
+
"model.layers.24.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
|
166 |
+
"model.layers.24.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
|
167 |
+
"model.layers.24.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
|
168 |
+
"model.layers.24.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
|
169 |
+
"model.layers.24.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
|
170 |
+
"model.layers.25.input_layernorm.weight": "model-00003-of-00003.safetensors",
|
171 |
+
"model.layers.25.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
|
172 |
+
"model.layers.25.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
|
173 |
+
"model.layers.25.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
|
174 |
+
"model.layers.25.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
|
175 |
+
"model.layers.25.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
|
176 |
+
"model.layers.25.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
|
177 |
+
"model.layers.25.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
|
178 |
+
"model.layers.25.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
|
179 |
+
"model.layers.26.input_layernorm.weight": "model-00003-of-00003.safetensors",
|
180 |
+
"model.layers.26.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
|
181 |
+
"model.layers.26.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
|
182 |
+
"model.layers.26.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
|
183 |
+
"model.layers.26.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
|
184 |
+
"model.layers.26.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
|
185 |
+
"model.layers.26.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
|
186 |
+
"model.layers.26.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
|
187 |
+
"model.layers.26.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
|
188 |
+
"model.layers.27.input_layernorm.weight": "model-00003-of-00003.safetensors",
|
189 |
+
"model.layers.27.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
|
190 |
+
"model.layers.27.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
|
191 |
+
"model.layers.27.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
|
192 |
+
"model.layers.27.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
|
193 |
+
"model.layers.27.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
|
194 |
+
"model.layers.27.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
|
195 |
+
"model.layers.27.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
|
196 |
+
"model.layers.27.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
|
197 |
+
"model.layers.28.input_layernorm.weight": "model-00003-of-00003.safetensors",
|
198 |
+
"model.layers.28.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
|
199 |
+
"model.layers.28.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
|
200 |
+
"model.layers.28.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
|
201 |
+
"model.layers.28.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
|
202 |
+
"model.layers.28.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
|
203 |
+
"model.layers.28.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
|
204 |
+
"model.layers.28.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
|
205 |
+
"model.layers.28.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
|
206 |
+
"model.layers.29.input_layernorm.weight": "model-00003-of-00003.safetensors",
|
207 |
+
"model.layers.29.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
|
208 |
+
"model.layers.29.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
|
209 |
+
"model.layers.29.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
|
210 |
+
"model.layers.29.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
|
211 |
+
"model.layers.29.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
|
212 |
+
"model.layers.29.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
|
213 |
+
"model.layers.29.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
|
214 |
+
"model.layers.29.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
|
215 |
+
"model.layers.3.input_layernorm.weight": "model-00001-of-00003.safetensors",
|
216 |
+
"model.layers.3.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
|
217 |
+
"model.layers.3.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
|
218 |
+
"model.layers.3.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
|
219 |
+
"model.layers.3.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
|
220 |
+
"model.layers.3.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
|
221 |
+
"model.layers.3.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
|
222 |
+
"model.layers.3.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
|
223 |
+
"model.layers.3.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
|
224 |
+
"model.layers.30.input_layernorm.weight": "model-00003-of-00003.safetensors",
|
225 |
+
"model.layers.30.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
|
226 |
+
"model.layers.30.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
|
227 |
+
"model.layers.30.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
|
228 |
+
"model.layers.30.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
|
229 |
+
"model.layers.30.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
|
230 |
+
"model.layers.30.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
|
231 |
+
"model.layers.30.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
|
232 |
+
"model.layers.30.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
|
233 |
+
"model.layers.31.input_layernorm.weight": "model-00003-of-00003.safetensors",
|
234 |
+
"model.layers.31.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
|
235 |
+
"model.layers.31.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
|
236 |
+
"model.layers.31.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
|
237 |
+
"model.layers.31.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
|
238 |
+
"model.layers.31.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
|
239 |
+
"model.layers.31.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
|
240 |
+
"model.layers.31.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
|
241 |
+
"model.layers.31.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
|
242 |
+
"model.layers.4.input_layernorm.weight": "model-00001-of-00003.safetensors",
|
243 |
+
"model.layers.4.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
|
244 |
+
"model.layers.4.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
|
245 |
+
"model.layers.4.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
|
246 |
+
"model.layers.4.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
|
247 |
+
"model.layers.4.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
|
248 |
+
"model.layers.4.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
|
249 |
+
"model.layers.4.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
|
250 |
+
"model.layers.4.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
|
251 |
+
"model.layers.5.input_layernorm.weight": "model-00001-of-00003.safetensors",
|
252 |
+
"model.layers.5.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
|
253 |
+
"model.layers.5.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
|
254 |
+
"model.layers.5.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
|
255 |
+
"model.layers.5.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
|
256 |
+
"model.layers.5.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
|
257 |
+
"model.layers.5.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
|
258 |
+
"model.layers.5.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
|
259 |
+
"model.layers.5.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
|
260 |
+
"model.layers.6.input_layernorm.weight": "model-00001-of-00003.safetensors",
|
261 |
+
"model.layers.6.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
|
262 |
+
"model.layers.6.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
|
263 |
+
"model.layers.6.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
|
264 |
+
"model.layers.6.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
|
265 |
+
"model.layers.6.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
|
266 |
+
"model.layers.6.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
|
267 |
+
"model.layers.6.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
|
268 |
+
"model.layers.6.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
|
269 |
+
"model.layers.7.input_layernorm.weight": "model-00001-of-00003.safetensors",
|
270 |
+
"model.layers.7.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
|
271 |
+
"model.layers.7.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
|
272 |
+
"model.layers.7.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
|
273 |
+
"model.layers.7.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
|
274 |
+
"model.layers.7.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
|
275 |
+
"model.layers.7.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
|
276 |
+
"model.layers.7.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
|
277 |
+
"model.layers.7.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
|
278 |
+
"model.layers.8.input_layernorm.weight": "model-00001-of-00003.safetensors",
|
279 |
+
"model.layers.8.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
|
280 |
+
"model.layers.8.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
|
281 |
+
"model.layers.8.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
|
282 |
+
"model.layers.8.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
|
283 |
+
"model.layers.8.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
|
284 |
+
"model.layers.8.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
|
285 |
+
"model.layers.8.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
|
286 |
+
"model.layers.8.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
|
287 |
+
"model.layers.9.input_layernorm.weight": "model-00001-of-00003.safetensors",
|
288 |
+
"model.layers.9.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
|
289 |
+
"model.layers.9.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
|
290 |
+
"model.layers.9.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
|
291 |
+
"model.layers.9.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
|
292 |
+
"model.layers.9.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
|
293 |
+
"model.layers.9.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
|
294 |
+
"model.layers.9.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
|
295 |
+
"model.layers.9.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
|
296 |
+
"model.norm.weight": "model-00003-of-00003.safetensors"
|
297 |
+
}
|
298 |
+
}
|
sparsification_sftt.py
ADDED
@@ -0,0 +1,1509 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import TrainerCallback, Trainer
|
2 |
+
from trl import SFTTrainer, DataCollatorForCompletionOnlyLM
|
3 |
+
from peft import PeftModel
|
4 |
+
from datasets import Dataset
|
5 |
+
from transformers.utils import is_sagemaker_mp_enabled, is_sagemaker_dp_enabled
|
6 |
+
from typing import Any, Dict, Union, Optional, Tuple
|
7 |
+
from torch.nn import MSELoss
|
8 |
+
from transformers.utils import is_flash_attn_2_available, logging
|
9 |
+
import inspect
|
10 |
+
import warnings
|
11 |
+
import math
|
12 |
+
import torch
|
13 |
+
import torch.nn as nn
|
14 |
+
import torch.nn.functional as F
|
15 |
+
import matplotlib.pyplot as plt
|
16 |
+
import numpy as np
|
17 |
+
import time
|
18 |
+
import os
|
19 |
+
import copy
|
20 |
+
|
21 |
+
from transformers.models.mistral.modeling_mistral import (
|
22 |
+
MistralMLP,
|
23 |
+
MistralAttention,
|
24 |
+
MistralModel,
|
25 |
+
MistralDecoderLayer,
|
26 |
+
MistralConfig,
|
27 |
+
MISTRAL_ATTENTION_CLASSES,
|
28 |
+
MistralRMSNorm,
|
29 |
+
MistralForCausalLM,
|
30 |
+
MistralFlashAttention2,
|
31 |
+
)
|
32 |
+
from experiments.models.sparse_mistral.svd_router import (
|
33 |
+
low_rank_approximation,
|
34 |
+
SparsePredictor,
|
35 |
+
)
|
36 |
+
from utils.utils import (
|
37 |
+
print_size_of_model,
|
38 |
+
is_running_deepspeed,
|
39 |
+
is_mainprocess,
|
40 |
+
get_datetime,
|
41 |
+
ds_print,
|
42 |
+
)
|
43 |
+
|
44 |
+
if is_flash_attn_2_available():
|
45 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
46 |
+
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
|
47 |
+
|
48 |
+
_flash_supports_window_size = "window_size" in list(
|
49 |
+
inspect.signature(flash_attn_func).parameters
|
50 |
+
)
|
51 |
+
logger = logging.get_logger(__name__)
|
52 |
+
|
53 |
+
|
54 |
+
class SparseSFTTTrainer(SFTTrainer):
|
55 |
+
def __init__(self, *args, **kwargs):
|
56 |
+
self.regularization_coefficient = kwargs.pop("regularization_coefficient", 10)
|
57 |
+
self.use_sparse_regularization = kwargs.pop("use_sparse_regularization", False)
|
58 |
+
self.use_spm_loss = False
|
59 |
+
self.freeze_original_weights = False
|
60 |
+
self.regularization_type = kwargs.pop(
|
61 |
+
"regularization_type", "L1 positive activation"
|
62 |
+
)
|
63 |
+
assert self.regularization_type in [
|
64 |
+
"L2 activation",
|
65 |
+
"L1 positive activation",
|
66 |
+
], f"Invalid regularization type: {self.regularization_type}"
|
67 |
+
self.sparse_layers = []
|
68 |
+
self.sparse_decoder_layers = []
|
69 |
+
super(SparseSFTTTrainer, self).__init__(*args, **kwargs)
|
70 |
+
|
71 |
+
def initialize_sparse_silu_layers(self, model):
|
72 |
+
self.sparse_layers = [
|
73 |
+
m for m in model.modules() if isinstance(m, MistralSparseSiluMLP)
|
74 |
+
]
|
75 |
+
|
76 |
+
def initialize_sparse_decoder_layers(self, model):
|
77 |
+
self.sparse_decoder_layers = [
|
78 |
+
m for m in model.modules() if isinstance(m, SparseMistralDecoderLayer)
|
79 |
+
]
|
80 |
+
|
81 |
+
def training_step(
|
82 |
+
self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]]
|
83 |
+
) -> torch.Tensor:
|
84 |
+
"""
|
85 |
+
Override the huggingface's training_step function to add a regularization term.
|
86 |
+
A regularization term is computed with intermediate values, which are freed after "backward()."
|
87 |
+
You need to set `retain_graph=True` inside `backward` function to keep the values.
|
88 |
+
"""
|
89 |
+
model.train()
|
90 |
+
inputs = self._prepare_inputs(inputs)
|
91 |
+
|
92 |
+
with self.compute_loss_context_manager():
|
93 |
+
loss = self.compute_loss(model, inputs)
|
94 |
+
|
95 |
+
if self.args.n_gpu > 1:
|
96 |
+
loss = loss.mean() # mean() to average on multi-gpu parallel training
|
97 |
+
if not self.freeze_original_weights:
|
98 |
+
if loss is not None:
|
99 |
+
self.accelerator.backward(loss, retain_graph=False)
|
100 |
+
|
101 |
+
if self.use_sparse_regularization:
|
102 |
+
regularization_loss = self.compute_regularization(model)
|
103 |
+
if self.args.n_gpu > 1:
|
104 |
+
regularization_loss = regularization_loss.mean()
|
105 |
+
if regularization_loss is not None:
|
106 |
+
self.accelerator.backward(regularization_loss, retain_graph=True)
|
107 |
+
loss += regularization_loss
|
108 |
+
|
109 |
+
if self.use_spm_loss:
|
110 |
+
spm_loss = self.compute_spm_loss(model)
|
111 |
+
if self.args.n_gpu > 1:
|
112 |
+
spm_loss = spm_loss.mean()
|
113 |
+
if spm_loss is not None:
|
114 |
+
self.accelerator.backward(spm_loss, retain_graph=False)
|
115 |
+
loss += spm_loss
|
116 |
+
|
117 |
+
return loss.detach() / self.args.gradient_accumulation_steps
|
118 |
+
|
119 |
+
def compute_regularization(self, model):
|
120 |
+
"""
|
121 |
+
Compute a sparse regularization loss for SiLU
|
122 |
+
"""
|
123 |
+
loss = 0
|
124 |
+
if len(self.sparse_layers) == 0:
|
125 |
+
self.initialize_sparse_silu_layers(model)
|
126 |
+
num_layers = len(self.sparse_layers)
|
127 |
+
|
128 |
+
for module in self.sparse_layers:
|
129 |
+
if module.activation_norm is not None:
|
130 |
+
loss += module.activation_norm
|
131 |
+
|
132 |
+
loss /= num_layers
|
133 |
+
loss *= self.regularization_coefficient
|
134 |
+
|
135 |
+
if self.state.global_step % 20 == 0 and loss != 0:
|
136 |
+
print("Negative relularizer loss: ", loss.item())
|
137 |
+
return loss
|
138 |
+
|
139 |
+
def compute_spm_loss(self, model):
|
140 |
+
loss = 0
|
141 |
+
if len(self.sparse_decoder_layers) == 0:
|
142 |
+
self.initialize_sparse_decoder_layers(model)
|
143 |
+
for module in self.sparse_decoder_layers:
|
144 |
+
if module.distill_loss != None:
|
145 |
+
loss += module.distill_loss
|
146 |
+
if self.state.global_step % 20 == 0 and loss != 0:
|
147 |
+
print("Sparse Predictor Distillation loss: ", loss.item())
|
148 |
+
return loss
|
149 |
+
|
150 |
+
# def compute_loss(self, model, inputs, return_outputs=False):
|
151 |
+
# loss = super().compute_loss(model, inputs, return_outputs)
|
152 |
+
#
|
153 |
+
# if is_sagemaker_mp_enabled():
|
154 |
+
# import smdistributed.modelparallel.torch as smp
|
155 |
+
# @smp.step()
|
156 |
+
# def smp_forward_backward(model, inputs, gradient_accumulation_steps=1):
|
157 |
+
# outputs = model(**inputs)
|
158 |
+
# loss = outputs["loss"] if isinstance(outputs, dict) else outputs[0]
|
159 |
+
# loss /= gradient_accumulation_steps
|
160 |
+
# model.backward(loss)
|
161 |
+
# return loss
|
162 |
+
#
|
163 |
+
# loss_mb = smp_forward_backward(
|
164 |
+
# model, inputs, self.args.gradient_accumulation_steps
|
165 |
+
# )
|
166 |
+
# if self.use_sparse_regularization:
|
167 |
+
# return loss_mb.reduce_mean().detach().to(
|
168 |
+
# self.args.device
|
169 |
+
# ) + self.regularization_coefficient * self.compute_regularization(model)
|
170 |
+
# else:
|
171 |
+
# return loss_mb.reduce_mean().detach().to(self)
|
172 |
+
#
|
173 |
+
# if return_outputs:
|
174 |
+
# classification_loss, outputs = loss
|
175 |
+
# else:
|
176 |
+
# classification_loss = loss
|
177 |
+
#
|
178 |
+
# loss = classification_loss
|
179 |
+
# if self.use_sparse_regularization:
|
180 |
+
# regularization_loss = self.compute_regularization(model)
|
181 |
+
# loss += self.regularization_coefficient * regularization_loss
|
182 |
+
#
|
183 |
+
# return (loss, outputs) if return_outputs else loss
|
184 |
+
|
185 |
+
|
186 |
+
class SparseTrainer(Trainer):
|
187 |
+
def __init__(self, *args, **kwargs):
|
188 |
+
self.regularization_coefficient = kwargs.pop("regularization_coefficient", 10)
|
189 |
+
self.use_sparse_regularization = kwargs.pop("use_sparse_regularization", False)
|
190 |
+
self.use_spm_loss = False
|
191 |
+
self.freeze_original_weights = False
|
192 |
+
self.regularization_type = kwargs.pop(
|
193 |
+
"regularization_type", "L1 positive activation"
|
194 |
+
)
|
195 |
+
assert self.regularization_type in [
|
196 |
+
"L2 activation",
|
197 |
+
"L1 positive activation",
|
198 |
+
], f"Invalid regularization type: {self.regularization_type}"
|
199 |
+
self.sparse_layers = []
|
200 |
+
self.sparse_decoder_layers = []
|
201 |
+
super(SparseTrainer, self).__init__(*args, **kwargs)
|
202 |
+
|
203 |
+
def initialize_sparse_silu_layers(self, model):
|
204 |
+
self.sparse_layers = [
|
205 |
+
m for m in model.modules() if isinstance(m, MistralSparseSiluMLP)
|
206 |
+
]
|
207 |
+
|
208 |
+
def initialize_sparse_decoder_layers(self, model):
|
209 |
+
self.sparse_decoder_layers = [
|
210 |
+
m for m in model.modules() if isinstance(m, SparseMistralDecoderLayer)
|
211 |
+
]
|
212 |
+
|
213 |
+
def training_step(
|
214 |
+
self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]]
|
215 |
+
) -> torch.Tensor:
|
216 |
+
"""
|
217 |
+
Override the huggingface's training_step function to add a regularization term.
|
218 |
+
A regularization term is computed with intermediate values, which are freed after "backward()."
|
219 |
+
You need to set `retain_graph=True` inside `backward` function to keep the values.
|
220 |
+
"""
|
221 |
+
model.train()
|
222 |
+
inputs = self._prepare_inputs(inputs)
|
223 |
+
|
224 |
+
with self.compute_loss_context_manager():
|
225 |
+
loss = self.compute_loss(model, inputs)
|
226 |
+
|
227 |
+
if self.args.n_gpu > 1:
|
228 |
+
loss = loss.mean() # mean() to average on multi-gpu parallel training
|
229 |
+
if not self.freeze_original_weights:
|
230 |
+
if loss is not None:
|
231 |
+
self.accelerator.backward(loss, retain_graph=False)
|
232 |
+
|
233 |
+
if self.use_sparse_regularization:
|
234 |
+
regularization_loss = self.compute_regularization(model)
|
235 |
+
if self.args.n_gpu > 1:
|
236 |
+
regularization_loss = regularization_loss.mean()
|
237 |
+
if regularization_loss is not None:
|
238 |
+
self.accelerator.backward(regularization_loss, retain_graph=True)
|
239 |
+
loss += regularization_loss
|
240 |
+
|
241 |
+
if self.use_spm_loss:
|
242 |
+
spm_loss = self.compute_spm_loss(model)
|
243 |
+
if self.args.n_gpu > 1:
|
244 |
+
spm_loss = spm_loss.mean()
|
245 |
+
if spm_loss is not None:
|
246 |
+
self.accelerator.backward(spm_loss, retain_graph=False)
|
247 |
+
loss += spm_loss
|
248 |
+
|
249 |
+
return loss.detach() / self.args.gradient_accumulation_steps
|
250 |
+
|
251 |
+
def compute_regularization(self, model):
|
252 |
+
"""
|
253 |
+
Compute a sparse regularization loss for SiLU
|
254 |
+
"""
|
255 |
+
loss = 0
|
256 |
+
if len(self.sparse_layers) == 0:
|
257 |
+
self.initialize_sparse_silu_layers(model)
|
258 |
+
num_layers = len(self.sparse_layers)
|
259 |
+
|
260 |
+
for module in self.sparse_layers:
|
261 |
+
if module.activation_norm is not None:
|
262 |
+
loss += module.activation_norm
|
263 |
+
|
264 |
+
loss /= num_layers
|
265 |
+
loss *= self.regularization_coefficient
|
266 |
+
|
267 |
+
if self.state.global_step % 20 == 0 and loss != 0:
|
268 |
+
print("Negative relularizer loss: ", loss.item())
|
269 |
+
return loss
|
270 |
+
|
271 |
+
def compute_spm_loss(self, model):
|
272 |
+
loss = 0
|
273 |
+
if len(self.sparse_decoder_layers) == 0:
|
274 |
+
self.initialize_sparse_decoder_layers(model)
|
275 |
+
for module in self.sparse_decoder_layers:
|
276 |
+
if module.distill_loss != None:
|
277 |
+
loss += module.distill_loss
|
278 |
+
if self.state.global_step % 20 == 0 and loss != 0:
|
279 |
+
print("Sparse Predictor Distillation loss: ", loss.item())
|
280 |
+
return loss
|
281 |
+
|
282 |
+
|
283 |
+
class SparseSiLU(nn.SiLU):
|
284 |
+
def __init__(self, threshold):
|
285 |
+
super(SparseSiLU, self).__init__()
|
286 |
+
self.threshold = threshold
|
287 |
+
self.m = nn.Threshold(self.threshold, 0)
|
288 |
+
|
289 |
+
def set_new_threshold(self, threshold):
|
290 |
+
self.threshold = threshold
|
291 |
+
self.m = nn.Threshold(threshold, 0)
|
292 |
+
|
293 |
+
def forward(self, x):
|
294 |
+
act = super(SparseSiLU, self).forward(x)
|
295 |
+
return self.m(act) - self.m(-act)
|
296 |
+
|
297 |
+
|
298 |
+
def rotate_half(x):
|
299 |
+
"""Rotates half the hidden dims of the input."""
|
300 |
+
x1 = x[..., : x.shape[-1] // 2]
|
301 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
302 |
+
return torch.cat((-x2, x1), dim=-1)
|
303 |
+
|
304 |
+
|
305 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
|
306 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
307 |
+
|
308 |
+
Args:
|
309 |
+
q (`torch.Tensor`): The query tensor.
|
310 |
+
k (`torch.Tensor`): The key tensor.
|
311 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
312 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
313 |
+
position_ids (`torch.Tensor`):
|
314 |
+
The position indices of the tokens corresponding to the query and key tensors. For example, this can be
|
315 |
+
used to pass offsetted position ids when working with a KV-cache.
|
316 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
317 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
318 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
319 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
320 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
321 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
322 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
323 |
+
Returns:
|
324 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
325 |
+
"""
|
326 |
+
cos = cos[position_ids].unsqueeze(unsqueeze_dim)
|
327 |
+
sin = sin[position_ids].unsqueeze(unsqueeze_dim)
|
328 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
329 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
330 |
+
return q_embed, k_embed
|
331 |
+
|
332 |
+
|
333 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
334 |
+
"""
|
335 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
336 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
337 |
+
"""
|
338 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
339 |
+
if n_rep == 1:
|
340 |
+
return hidden_states
|
341 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(
|
342 |
+
batch, num_key_value_heads, n_rep, slen, head_dim
|
343 |
+
)
|
344 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
345 |
+
|
346 |
+
|
347 |
+
def _get_unpad_data(attention_mask):
|
348 |
+
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
|
349 |
+
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
350 |
+
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
351 |
+
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
|
352 |
+
return (
|
353 |
+
indices,
|
354 |
+
cu_seqlens,
|
355 |
+
max_seqlen_in_batch,
|
356 |
+
)
|
357 |
+
|
358 |
+
|
359 |
+
class SparseMistralAttention(MistralFlashAttention2):
|
360 |
+
"""
|
361 |
+
Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
|
362 |
+
and "Generating Long Sequences with Sparse Transformers".
|
363 |
+
"""
|
364 |
+
|
365 |
+
def __init__(self, *args, **kwargs):
|
366 |
+
super().__init__(*args, **kwargs)
|
367 |
+
self.counts = 0
|
368 |
+
|
369 |
+
def forward(
|
370 |
+
self,
|
371 |
+
hidden_states: torch.Tensor,
|
372 |
+
attention_mask: Optional[torch.Tensor] = None,
|
373 |
+
position_ids: Optional[torch.LongTensor] = None,
|
374 |
+
past_key_value: Optional = None,
|
375 |
+
output_attentions: bool = False,
|
376 |
+
use_cache: bool = False,
|
377 |
+
**kwargs,
|
378 |
+
):
|
379 |
+
if "padding_mask" in kwargs:
|
380 |
+
warnings.warn(
|
381 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
382 |
+
)
|
383 |
+
|
384 |
+
# overwrite attention_mask with padding_mask
|
385 |
+
attention_mask = kwargs.pop("padding_mask")
|
386 |
+
bsz, q_len, _ = hidden_states.size()
|
387 |
+
mask = abs(hidden_states - hidden_states.mean()) < 0.8 * hidden_states.std()
|
388 |
+
hidden_states[mask] = 0
|
389 |
+
if self.counts <= 1:
|
390 |
+
print(f"Attention {self.layer_idx}: ", (hidden_states==0).float().mean())
|
391 |
+
self.counts += 1
|
392 |
+
|
393 |
+
query_states = self.q_proj(hidden_states)
|
394 |
+
key_states = self.k_proj(hidden_states)
|
395 |
+
value_states = self.v_proj(hidden_states)
|
396 |
+
|
397 |
+
query_states = query_states.view(
|
398 |
+
bsz, q_len, self.num_heads, self.head_dim
|
399 |
+
).transpose(1, 2)
|
400 |
+
key_states = key_states.view(
|
401 |
+
bsz, q_len, self.num_key_value_heads, self.head_dim
|
402 |
+
).transpose(1, 2)
|
403 |
+
value_states = value_states.view(
|
404 |
+
bsz, q_len, self.num_key_value_heads, self.head_dim
|
405 |
+
).transpose(1, 2)
|
406 |
+
|
407 |
+
kv_seq_len = key_states.shape[-2]
|
408 |
+
if past_key_value is not None:
|
409 |
+
if self.layer_idx is None:
|
410 |
+
raise ValueError(
|
411 |
+
f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
|
412 |
+
"for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
|
413 |
+
"with a layer index."
|
414 |
+
)
|
415 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
416 |
+
|
417 |
+
# Because the input can be padded, the absolute sequence length depends on the max position id.
|
418 |
+
rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
|
419 |
+
cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
|
420 |
+
|
421 |
+
query_states, key_states = apply_rotary_pos_emb(
|
422 |
+
query_states, key_states, cos, sin, position_ids
|
423 |
+
)
|
424 |
+
|
425 |
+
use_sliding_windows = (
|
426 |
+
_flash_supports_window_size
|
427 |
+
and getattr(self.config, "sliding_window", None) is not None
|
428 |
+
and kv_seq_len > self.config.sliding_window
|
429 |
+
)
|
430 |
+
|
431 |
+
if not _flash_supports_window_size:
|
432 |
+
logger.warning_once(
|
433 |
+
"The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
|
434 |
+
" make sure to upgrade flash-attn library."
|
435 |
+
)
|
436 |
+
|
437 |
+
if past_key_value is not None:
|
438 |
+
# Activate slicing cache only if the config has a value `sliding_windows` attribute
|
439 |
+
cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
|
440 |
+
if (
|
441 |
+
getattr(self.config, "sliding_window", None) is not None
|
442 |
+
and kv_seq_len > self.config.sliding_window
|
443 |
+
and cache_has_contents
|
444 |
+
):
|
445 |
+
slicing_tokens = 1 - self.config.sliding_window
|
446 |
+
|
447 |
+
past_key = past_key_value[self.layer_idx][0]
|
448 |
+
past_value = past_key_value[self.layer_idx][1]
|
449 |
+
|
450 |
+
past_key = past_key[:, :, slicing_tokens:, :].contiguous()
|
451 |
+
past_value = past_value[:, :, slicing_tokens:, :].contiguous()
|
452 |
+
|
453 |
+
if past_key.shape[-2] != self.config.sliding_window - 1:
|
454 |
+
raise ValueError(
|
455 |
+
f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
|
456 |
+
f" {past_key.shape}"
|
457 |
+
)
|
458 |
+
|
459 |
+
if attention_mask is not None:
|
460 |
+
attention_mask = attention_mask[:, slicing_tokens:]
|
461 |
+
attention_mask = torch.cat(
|
462 |
+
[attention_mask, torch.ones_like(attention_mask[:, -1:])],
|
463 |
+
dim=-1,
|
464 |
+
)
|
465 |
+
|
466 |
+
cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
467 |
+
key_states, value_states = past_key_value.update(
|
468 |
+
key_states, value_states, self.layer_idx, cache_kwargs
|
469 |
+
)
|
470 |
+
|
471 |
+
# repeat k/v heads if n_kv_heads < n_heads
|
472 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
473 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
474 |
+
dropout_rate = 0.0 if not self.training else self.attention_dropout
|
475 |
+
|
476 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
477 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
478 |
+
# cast them back in float16 just to be sure everything works as expected.
|
479 |
+
input_dtype = query_states.dtype
|
480 |
+
if input_dtype == torch.float32:
|
481 |
+
if torch.is_autocast_enabled():
|
482 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
483 |
+
# Handle the case where the model is quantized
|
484 |
+
elif hasattr(self.config, "_pre_quantization_dtype"):
|
485 |
+
target_dtype = self.config._pre_quantization_dtype
|
486 |
+
else:
|
487 |
+
target_dtype = self.q_proj.weight.dtype
|
488 |
+
|
489 |
+
logger.warning_once(
|
490 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
491 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
492 |
+
f" {target_dtype}."
|
493 |
+
)
|
494 |
+
|
495 |
+
query_states = query_states.to(target_dtype)
|
496 |
+
key_states = key_states.to(target_dtype)
|
497 |
+
value_states = value_states.to(target_dtype)
|
498 |
+
|
499 |
+
# Reashape to the expected shape for Flash Attention
|
500 |
+
query_states = query_states.transpose(1, 2)
|
501 |
+
key_states = key_states.transpose(1, 2)
|
502 |
+
value_states = value_states.transpose(1, 2)
|
503 |
+
|
504 |
+
attn_output = self._flash_attention_forward(
|
505 |
+
query_states,
|
506 |
+
key_states,
|
507 |
+
value_states,
|
508 |
+
attention_mask,
|
509 |
+
q_len,
|
510 |
+
dropout=dropout_rate,
|
511 |
+
use_sliding_windows=use_sliding_windows,
|
512 |
+
)
|
513 |
+
|
514 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
|
515 |
+
attn_output = self.o_proj(attn_output)
|
516 |
+
|
517 |
+
if not output_attentions:
|
518 |
+
attn_weights = None
|
519 |
+
|
520 |
+
return attn_output, attn_weights, past_key_value
|
521 |
+
|
522 |
+
def _flash_attention_forward(
|
523 |
+
self,
|
524 |
+
query_states,
|
525 |
+
key_states,
|
526 |
+
value_states,
|
527 |
+
attention_mask,
|
528 |
+
query_length,
|
529 |
+
dropout=0.0,
|
530 |
+
softmax_scale=None,
|
531 |
+
use_sliding_windows=False,
|
532 |
+
):
|
533 |
+
"""
|
534 |
+
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
|
535 |
+
first unpad the input, then computes the attention scores and pad the final attention scores.
|
536 |
+
|
537 |
+
Args:
|
538 |
+
query_states (`torch.Tensor`):
|
539 |
+
Input query states to be passed to Flash Attention API
|
540 |
+
key_states (`torch.Tensor`):
|
541 |
+
Input key states to be passed to Flash Attention API
|
542 |
+
value_states (`torch.Tensor`):
|
543 |
+
Input value states to be passed to Flash Attention API
|
544 |
+
attention_mask (`torch.Tensor`):
|
545 |
+
The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
|
546 |
+
position of padding tokens and 1 for the position of non-padding tokens.
|
547 |
+
dropout (`float`):
|
548 |
+
Attention dropout
|
549 |
+
softmax_scale (`float`, *optional*):
|
550 |
+
The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
|
551 |
+
use_sliding_windows (`bool`, *optional*):
|
552 |
+
Whether to activate sliding window attention.
|
553 |
+
"""
|
554 |
+
if not self._flash_attn_uses_top_left_mask:
|
555 |
+
causal = self.is_causal
|
556 |
+
else:
|
557 |
+
# TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
|
558 |
+
causal = self.is_causal and query_length != 1
|
559 |
+
|
560 |
+
# Contains at least one padding token in the sequence
|
561 |
+
if attention_mask is not None:
|
562 |
+
batch_size = query_states.shape[0]
|
563 |
+
(
|
564 |
+
query_states,
|
565 |
+
key_states,
|
566 |
+
value_states,
|
567 |
+
indices_q,
|
568 |
+
cu_seq_lens,
|
569 |
+
max_seq_lens,
|
570 |
+
) = self._upad_input(
|
571 |
+
query_states, key_states, value_states, attention_mask, query_length
|
572 |
+
)
|
573 |
+
|
574 |
+
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
575 |
+
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
576 |
+
|
577 |
+
if not use_sliding_windows:
|
578 |
+
attn_output_unpad = flash_attn_varlen_func(
|
579 |
+
query_states,
|
580 |
+
key_states,
|
581 |
+
value_states,
|
582 |
+
cu_seqlens_q=cu_seqlens_q,
|
583 |
+
cu_seqlens_k=cu_seqlens_k,
|
584 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
585 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
586 |
+
dropout_p=dropout,
|
587 |
+
softmax_scale=softmax_scale,
|
588 |
+
causal=causal,
|
589 |
+
)
|
590 |
+
else:
|
591 |
+
attn_output_unpad = flash_attn_varlen_func(
|
592 |
+
query_states,
|
593 |
+
key_states,
|
594 |
+
value_states,
|
595 |
+
cu_seqlens_q=cu_seqlens_q,
|
596 |
+
cu_seqlens_k=cu_seqlens_k,
|
597 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
598 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
599 |
+
dropout_p=dropout,
|
600 |
+
softmax_scale=softmax_scale,
|
601 |
+
causal=causal,
|
602 |
+
window_size=(
|
603 |
+
self.config.sliding_window,
|
604 |
+
self.config.sliding_window,
|
605 |
+
),
|
606 |
+
)
|
607 |
+
|
608 |
+
attn_output = pad_input(
|
609 |
+
attn_output_unpad, indices_q, batch_size, query_length
|
610 |
+
)
|
611 |
+
else:
|
612 |
+
if not use_sliding_windows:
|
613 |
+
attn_output = flash_attn_func(
|
614 |
+
query_states,
|
615 |
+
key_states,
|
616 |
+
value_states,
|
617 |
+
dropout,
|
618 |
+
softmax_scale=softmax_scale,
|
619 |
+
causal=causal,
|
620 |
+
)
|
621 |
+
else:
|
622 |
+
attn_output = flash_attn_func(
|
623 |
+
query_states,
|
624 |
+
key_states,
|
625 |
+
value_states,
|
626 |
+
dropout,
|
627 |
+
softmax_scale=softmax_scale,
|
628 |
+
causal=causal,
|
629 |
+
window_size=(
|
630 |
+
self.config.sliding_window,
|
631 |
+
self.config.sliding_window,
|
632 |
+
),
|
633 |
+
)
|
634 |
+
|
635 |
+
return attn_output
|
636 |
+
|
637 |
+
def _upad_input(
|
638 |
+
self, query_layer, key_layer, value_layer, attention_mask, query_length
|
639 |
+
):
|
640 |
+
batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
|
641 |
+
|
642 |
+
# On the first iteration we need to properly re-create the padding mask
|
643 |
+
# by slicing it on the proper place
|
644 |
+
if kv_seq_len != attention_mask.shape[-1]:
|
645 |
+
attention_mask_num_tokens = attention_mask.shape[-1]
|
646 |
+
attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
|
647 |
+
|
648 |
+
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
|
649 |
+
|
650 |
+
key_layer = index_first_axis(
|
651 |
+
key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
|
652 |
+
)
|
653 |
+
value_layer = index_first_axis(
|
654 |
+
value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
|
655 |
+
)
|
656 |
+
|
657 |
+
if query_length == kv_seq_len:
|
658 |
+
query_layer = index_first_axis(
|
659 |
+
query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim),
|
660 |
+
indices_k,
|
661 |
+
)
|
662 |
+
cu_seqlens_q = cu_seqlens_k
|
663 |
+
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
664 |
+
indices_q = indices_k
|
665 |
+
elif query_length == 1:
|
666 |
+
max_seqlen_in_batch_q = 1
|
667 |
+
cu_seqlens_q = torch.arange(
|
668 |
+
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
669 |
+
) # There is a memcpy here, that is very bad.
|
670 |
+
indices_q = cu_seqlens_q[:-1]
|
671 |
+
query_layer = query_layer.squeeze(1)
|
672 |
+
else:
|
673 |
+
# The -q_len: slice assumes left padding.
|
674 |
+
attention_mask = attention_mask[:, -query_length:]
|
675 |
+
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
|
676 |
+
query_layer, attention_mask
|
677 |
+
)
|
678 |
+
|
679 |
+
return (
|
680 |
+
query_layer,
|
681 |
+
key_layer,
|
682 |
+
value_layer,
|
683 |
+
indices_q,
|
684 |
+
(cu_seqlens_q, cu_seqlens_k),
|
685 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
686 |
+
)
|
687 |
+
|
688 |
+
# def forward(
|
689 |
+
# self,
|
690 |
+
# hidden_states: torch.Tensor,
|
691 |
+
# attention_mask: Optional[torch.Tensor] = None,
|
692 |
+
# position_ids: Optional[torch.LongTensor] = None,
|
693 |
+
# past_key_value: Optional = None,
|
694 |
+
# output_attentions: bool = False,
|
695 |
+
# use_cache: bool = False,
|
696 |
+
# **kwargs,
|
697 |
+
# ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
698 |
+
# if "padding_mask" in kwargs:
|
699 |
+
# warnings.warn(
|
700 |
+
# "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
701 |
+
# )
|
702 |
+
# bsz, q_len, _ = hidden_states.size()
|
703 |
+
# mask = abs(hidden_states - hidden_states.mean()) < 0.8 * hidden_states.std()
|
704 |
+
# hidden_states[mask] = 0
|
705 |
+
# if self.counts <= 1:
|
706 |
+
# print(f"Attention {self.layer_idx}: ", (hidden_states==0).float().mean())
|
707 |
+
# self.counts += 1
|
708 |
+
#
|
709 |
+
# query_states = self.q_proj(hidden_states)
|
710 |
+
# key_states = self.k_proj(hidden_states)
|
711 |
+
# value_states = self.v_proj(hidden_states)
|
712 |
+
#
|
713 |
+
# query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
714 |
+
# key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
715 |
+
# value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
716 |
+
#
|
717 |
+
# kv_seq_len = key_states.shape[-2]
|
718 |
+
# if past_key_value is not None:
|
719 |
+
# if self.layer_idx is None:
|
720 |
+
# raise ValueError(
|
721 |
+
# f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
|
722 |
+
# "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
|
723 |
+
# "with a layer index."
|
724 |
+
# )
|
725 |
+
# kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
726 |
+
# cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
727 |
+
# query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
728 |
+
#
|
729 |
+
# if past_key_value is not None:
|
730 |
+
# cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
731 |
+
# key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
732 |
+
#
|
733 |
+
# # repeat k/v heads if n_kv_heads < n_heads
|
734 |
+
# key_states = repeat_kv(key_states, self.num_key_value_groups)
|
735 |
+
# value_states = repeat_kv(value_states, self.num_key_value_groups)
|
736 |
+
#
|
737 |
+
# attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
738 |
+
#
|
739 |
+
# if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
740 |
+
# raise ValueError(
|
741 |
+
# f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
|
742 |
+
# f" {attn_weights.size()}"
|
743 |
+
# )
|
744 |
+
#
|
745 |
+
# if attention_mask is not None:
|
746 |
+
# if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
747 |
+
# raise ValueError(
|
748 |
+
# f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
749 |
+
# )
|
750 |
+
#
|
751 |
+
# attn_weights = attn_weights + attention_mask
|
752 |
+
#
|
753 |
+
# # upcast attention to fp32
|
754 |
+
# attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
755 |
+
# attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
756 |
+
# attn_output = torch.matmul(attn_weights, value_states)
|
757 |
+
#
|
758 |
+
# if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
759 |
+
# raise ValueError(
|
760 |
+
# f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
761 |
+
# f" {attn_output.size()}"
|
762 |
+
# )
|
763 |
+
#
|
764 |
+
# attn_output = attn_output.transpose(1, 2).contiguous()
|
765 |
+
# attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
766 |
+
#
|
767 |
+
# attn_output = self.o_proj(attn_output)
|
768 |
+
#
|
769 |
+
# if not output_attentions:
|
770 |
+
# attn_weights = None
|
771 |
+
#
|
772 |
+
# return attn_output, attn_weights, past_key_value
|
773 |
+
|
774 |
+
|
775 |
+
class MistralSparseSiluMLP(MistralMLP):
|
776 |
+
def __init__(self, config, *args, **kwargs):
|
777 |
+
super().__init__(config)
|
778 |
+
self.swish_outputs = None
|
779 |
+
self.relu = nn.ReLU()
|
780 |
+
self.resilu = nn.Sequential(nn.SiLU())
|
781 |
+
|
782 |
+
self.kill_sparse_swish_outputs = False
|
783 |
+
self.dead_percentage = 0
|
784 |
+
self.is_stats = False
|
785 |
+
self.visit_counts = 0
|
786 |
+
|
787 |
+
# Hyperparameters to tune
|
788 |
+
self.dead_threshold = kwargs.pop("dead_threshold", 0)
|
789 |
+
self.pre_mlp_dead_threshold = kwargs.pop("pre_mlp_dead_threshold", 0)
|
790 |
+
self.use_sparse_regularization = kwargs.pop("use_sparse_regularization", True)
|
791 |
+
self.regularization_type = kwargs.pop(
|
792 |
+
"regularization_type", "L1 regularization"
|
793 |
+
)
|
794 |
+
self.regularization_threshold = kwargs.pop("regularization_threshold", 0.5)
|
795 |
+
self.use_relu = kwargs.pop("use_relu", False)
|
796 |
+
self.use_resilu = kwargs.pop("use_resilu", False)
|
797 |
+
self.activation_norm = None
|
798 |
+
|
799 |
+
# Activation Histograms
|
800 |
+
self.is_collect_histogram = False
|
801 |
+
num_bins = 1000
|
802 |
+
self.histogram_bins = torch.linspace(-1, 1, num_bins - 2)
|
803 |
+
self.histogram_bins = torch.cat(
|
804 |
+
[torch.tensor([-torch.inf]), self.histogram_bins, torch.tensor([torch.inf])]
|
805 |
+
)
|
806 |
+
self.pre_mlp_hist_counts = torch.zeros(num_bins - 1)
|
807 |
+
self.pre_act_hist_counts = torch.zeros(num_bins - 1)
|
808 |
+
self.post_act_hist_counts = torch.zeros(num_bins - 1)
|
809 |
+
self.t = 0
|
810 |
+
self.count = 0
|
811 |
+
self.agg_sparsity = 0
|
812 |
+
|
813 |
+
# Sparse activation function
|
814 |
+
self.sparse_act_fn = SparseSiLU(threshold=self.dead_threshold)
|
815 |
+
|
816 |
+
def activate_stats(self, is_collect_histogram: bool = True):
|
817 |
+
self.is_stats = True
|
818 |
+
self.dead_percentage = 0
|
819 |
+
self.visit_counts = 0
|
820 |
+
self.is_collect_histogram = is_collect_histogram
|
821 |
+
self.histogram_counts = torch.zeros(2000) # .to(self.down_proj.weight.device)
|
822 |
+
|
823 |
+
def deactivate_stats(self):
|
824 |
+
self.is_stats = False
|
825 |
+
|
826 |
+
def collect_stats(
|
827 |
+
self,
|
828 |
+
pre_mlp,
|
829 |
+
pre_activation,
|
830 |
+
post_activation,
|
831 |
+
):
|
832 |
+
start_time = time.time()
|
833 |
+
pre_activation = pre_activation.float().cpu().detach()
|
834 |
+
post_activation = post_activation.float().cpu().detach()
|
835 |
+
# self.histogram_bins=self.histogram_bins.to(pre_activation.device).type(pre_activation.dtype)
|
836 |
+
self.pre_mlp_hist_counts = torch.histogram(pre_mlp, bins=self.histogram_bins)[0]
|
837 |
+
self.pre_act_hist_counts += torch.histogram(
|
838 |
+
pre_activation, bins=self.histogram_bins
|
839 |
+
)[0]
|
840 |
+
self.post_act_hist_counts += torch.histogram(
|
841 |
+
torch.abs(post_activation), bins=self.histogram_bins
|
842 |
+
)[0]
|
843 |
+
self.t += time.time() - start_time
|
844 |
+
if self.visit_counts % 30 == 0:
|
845 |
+
print(f"Time taken to collect stats: {self.t}s.")
|
846 |
+
|
847 |
+
def forward(
|
848 |
+
self,
|
849 |
+
x,
|
850 |
+
sp_mask: torch.tensor = None,
|
851 |
+
):
|
852 |
+
"""
|
853 |
+
If kill_sparse_swish_outputs is set to False, this layer functions exactly like a normal MLP layer.
|
854 |
+
"""
|
855 |
+
if sp_mask != None: # When sparse mask is given
|
856 |
+
return self.down_proj(
|
857 |
+
self.sparse_act_fn(self.gate_proj(x) * sp_mask) * self.up_proj(x)
|
858 |
+
) # Todo: This doesn't accelerate runtime (instead slowing down)
|
859 |
+
|
860 |
+
elif self.use_relu or self.use_resilu:
|
861 |
+
if self.use_relu:
|
862 |
+
post_act = self.relu(self.gate_proj(x))
|
863 |
+
else:
|
864 |
+
post_act = self.resilu(self.gate_proj(x))
|
865 |
+
self.count += 1
|
866 |
+
if self.count <= 1:
|
867 |
+
print("USING RELU or ReSiLU!!!!")
|
868 |
+
|
869 |
+
if self.is_stats:
|
870 |
+
dead_neurons = post_act == 0
|
871 |
+
dead_percentage = dead_neurons.float().mean()
|
872 |
+
agg_sparsity = dead_neurons.all(dim=0).float().mean()
|
873 |
+
|
874 |
+
self.dead_percentage = (
|
875 |
+
self.dead_percentage * self.visit_counts + dead_percentage
|
876 |
+
) / (self.visit_counts + 1)
|
877 |
+
self.agg_sparsity = (
|
878 |
+
self.agg_sparsity * self.visit_counts + agg_sparsity
|
879 |
+
) / (self.visit_counts + 1)
|
880 |
+
self.visit_counts += 1
|
881 |
+
|
882 |
+
return self.down_proj(post_act * self.up_proj(x))
|
883 |
+
|
884 |
+
else:
|
885 |
+
self.count += 1
|
886 |
+
# x[abs(x) < 0.7 * x.std()] = 0
|
887 |
+
if self.count <= 1:
|
888 |
+
print("USING SparseSILU!!!!")
|
889 |
+
# print(x.mean(), x.std(), x.max(), x.min())
|
890 |
+
# print(f"pre mlp sparsity: {(x==0).float().mean()}")
|
891 |
+
pre_act = self.gate_proj(x)
|
892 |
+
post_act = self.act_fn(pre_act)
|
893 |
+
if self.kill_sparse_swish_outputs:
|
894 |
+
dead_neurons = post_act.abs() <= self.dead_threshold
|
895 |
+
# print("pre act sparsity: ", (pre_act==0).float().mean())
|
896 |
+
|
897 |
+
dead_percentage = dead_neurons.float().mean()
|
898 |
+
agg_sparsity = dead_neurons.all(dim=0).float().mean()
|
899 |
+
|
900 |
+
if self.is_stats:
|
901 |
+
self.dead_percentage = (
|
902 |
+
self.dead_percentage * self.visit_counts + dead_percentage
|
903 |
+
) / (self.visit_counts + 1)
|
904 |
+
self.agg_sparsity = (
|
905 |
+
self.agg_sparsity * self.visit_counts + agg_sparsity
|
906 |
+
) / (self.visit_counts + 1)
|
907 |
+
self.visit_counts += 1
|
908 |
+
|
909 |
+
self.a = dead_percentage
|
910 |
+
|
911 |
+
# print(self.agg_sparsity)
|
912 |
+
|
913 |
+
# Collect histogram stats
|
914 |
+
if (
|
915 |
+
self.is_collect_histogram
|
916 |
+
and pre_act.eq(0).float().mean() < 0.99
|
917 |
+
): # Padded dataset
|
918 |
+
self.collect_stats(x, pre_act, post_act)
|
919 |
+
|
920 |
+
post_act[dead_neurons] = 0
|
921 |
+
if self.count <= 1:
|
922 |
+
print(f"sparsity: {dead_percentage}/ pre-activation sparsity: {(x==0).float().mean()}")
|
923 |
+
|
924 |
+
out = self.down_proj(post_act * self.up_proj(x))
|
925 |
+
if self.use_sparse_regularization:
|
926 |
+
if self.regularization_type == "L1 regularization":
|
927 |
+
self.activation_norm = torch.abs(post_act)[
|
928 |
+
post_act < self.regularization_threshold
|
929 |
+
].mean()
|
930 |
+
elif self.regularization_type == "L2 regularization":
|
931 |
+
self.activation_norm = torch.sqrt(
|
932 |
+
torch.square(post_act)[post_act < self.regularization_threshold]
|
933 |
+
).mean()
|
934 |
+
|
935 |
+
return out
|
936 |
+
|
937 |
+
|
938 |
+
class SparseMistralDecoderLayer(MistralDecoderLayer):
|
939 |
+
def __init__(
|
940 |
+
self,
|
941 |
+
config: MistralConfig,
|
942 |
+
layer_idx: int,
|
943 |
+
decoder_layer: MistralDecoderLayer,
|
944 |
+
init_svd: bool = True,
|
945 |
+
*args,
|
946 |
+
**kwargs,
|
947 |
+
):
|
948 |
+
assert isinstance(
|
949 |
+
decoder_layer.mlp, MistralSparseSiluMLP
|
950 |
+
), f"{type(decoder_layer.mlp)} should MistralSparseSiluMLP."
|
951 |
+
|
952 |
+
super().__init__(config, layer_idx)
|
953 |
+
self.hidden_size = config.hidden_size
|
954 |
+
self.intermediate_size = config.intermediate_size
|
955 |
+
|
956 |
+
self.init_svd = init_svd
|
957 |
+
self.self_attn = decoder_layer.self_attn
|
958 |
+
|
959 |
+
self.mlp = decoder_layer.mlp
|
960 |
+
self.input_layernorm = decoder_layer.input_layernorm
|
961 |
+
self.post_attention_layernorm = decoder_layer.post_attention_layernorm
|
962 |
+
|
963 |
+
# Sparse predictor for mlp (initialized with SVD decomposed matrix)
|
964 |
+
self.low_rank = kwargs.pop("low_rank", 64)
|
965 |
+
self.sparse_act_func = decoder_layer.mlp.sparse_act_fn
|
966 |
+
|
967 |
+
print(
|
968 |
+
f"Setting {layer_idx}th mlp layer's sparse predictor... svd init: {init_svd}"
|
969 |
+
)
|
970 |
+
self.sp_mlp = low_rank_approximation(
|
971 |
+
decoder_layer.mlp.gate_proj,
|
972 |
+
act_func=self.sparse_act_func,
|
973 |
+
init_svd=init_svd,
|
974 |
+
)
|
975 |
+
self.use_async = kwargs.pop("use_async", False)
|
976 |
+
self.use_sparse_predictor = False
|
977 |
+
self.distill_loss = None
|
978 |
+
|
979 |
+
def forward(
|
980 |
+
self,
|
981 |
+
hidden_states: torch.Tensor,
|
982 |
+
attention_mask: Optional[torch.Tensor] = None,
|
983 |
+
position_ids: Optional[torch.LongTensor] = None,
|
984 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
985 |
+
output_attentions: Optional[bool] = False,
|
986 |
+
use_cache: Optional[bool] = False,
|
987 |
+
**kwargs,
|
988 |
+
) -> Tuple[
|
989 |
+
torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
|
990 |
+
]:
|
991 |
+
print("hidden_states shape: ", hidden_states.shape)
|
992 |
+
if "padding_mask" in kwargs:
|
993 |
+
warnings.warn(
|
994 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
995 |
+
)
|
996 |
+
|
997 |
+
residual = hidden_states
|
998 |
+
sp_mask = None
|
999 |
+
|
1000 |
+
if self.use_async:
|
1001 |
+
sp_mask = self.sp_mlp(hidden_states)
|
1002 |
+
|
1003 |
+
hidden_states = self.input_layernorm(hidden_states)
|
1004 |
+
|
1005 |
+
# Self Attention
|
1006 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
1007 |
+
hidden_states=hidden_states,
|
1008 |
+
attention_mask=attention_mask,
|
1009 |
+
position_ids=position_ids,
|
1010 |
+
past_key_value=past_key_value,
|
1011 |
+
output_attentions=output_attentions,
|
1012 |
+
use_cache=use_cache,
|
1013 |
+
)
|
1014 |
+
hidden_states = residual + hidden_states
|
1015 |
+
|
1016 |
+
# Fully Connected
|
1017 |
+
residual = hidden_states
|
1018 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
1019 |
+
|
1020 |
+
if not self.use_async:
|
1021 |
+
sp_mask = self.sp_mlp(hidden_states)
|
1022 |
+
|
1023 |
+
# Compute distillation loss
|
1024 |
+
gating_output = self.mlp.sparse_act_fn(self.mlp.gate_proj(hidden_states))
|
1025 |
+
loss_func = MSELoss()
|
1026 |
+
self.distill_loss = loss_func(sp_mask, gating_output)
|
1027 |
+
|
1028 |
+
# Convert sp mask into binary form
|
1029 |
+
sp_mask = sp_mask > 0
|
1030 |
+
|
1031 |
+
if self.training:
|
1032 |
+
sp_mask = None
|
1033 |
+
# if not self.use_sparse_predictor:
|
1034 |
+
# sp_mask = None
|
1035 |
+
|
1036 |
+
hidden_states = self.mlp(hidden_states, sp_mask)
|
1037 |
+
hidden_states = residual + hidden_states
|
1038 |
+
|
1039 |
+
outputs = (hidden_states,)
|
1040 |
+
|
1041 |
+
if output_attentions:
|
1042 |
+
outputs += (self_attn_weights,)
|
1043 |
+
|
1044 |
+
if use_cache:
|
1045 |
+
outputs += (present_key_value,)
|
1046 |
+
|
1047 |
+
return outputs
|
1048 |
+
|
1049 |
+
|
1050 |
+
class SparseMistralConfig(MistralConfig):
|
1051 |
+
model_type = "sparse_mistral"
|
1052 |
+
|
1053 |
+
def __init__(self, **kwargs):
|
1054 |
+
super().__init__(**kwargs)
|
1055 |
+
|
1056 |
+
|
1057 |
+
class SparseMistralforCausalLM(MistralForCausalLM):
|
1058 |
+
config_class = SparseMistralConfig
|
1059 |
+
|
1060 |
+
def __init__(self, config):
|
1061 |
+
super().__init__(config)
|
1062 |
+
self.config = config
|
1063 |
+
if config.use_sparse_model:
|
1064 |
+
self.apply_sparse_mlp()
|
1065 |
+
if config.thresholds is not None:
|
1066 |
+
for idx, m in enumerate(self.model.layers):
|
1067 |
+
if isinstance(m.mlp, MistralSparseSiluMLP):
|
1068 |
+
m.mlp.dead_threshold = config.thresholds[idx]
|
1069 |
+
m.mlp.sparse_act_fn.set_new_threshold(m.mlp.dead_threshold)
|
1070 |
+
m.mlp.kill_sparse_swish_outputs = True
|
1071 |
+
m.mlp.use_relu = getattr(config, "use_relu", False)
|
1072 |
+
m.mlp.use_resilu = getattr(config, "use_resilu", False)
|
1073 |
+
if config.use_sparse_predictor:
|
1074 |
+
self.apply_sparse_predictor(init_svd=config.init_svd)
|
1075 |
+
|
1076 |
+
def apply_sparse_mlp(self):
|
1077 |
+
apply_mistral_sparse_silu_mlp(
|
1078 |
+
self,
|
1079 |
+
config=self.config,
|
1080 |
+
use_sparse_regularization=self.config.use_sparse_regularization,
|
1081 |
+
)
|
1082 |
+
|
1083 |
+
def apply_sparse_predictor(self, init_svd: bool = True):
|
1084 |
+
apply_mistral_sparse_decoder_layer(self, config=self.config, init_svd=init_svd)
|
1085 |
+
|
1086 |
+
|
1087 |
+
class GracefulRegularizationScheduler(TrainerCallback):
|
1088 |
+
def __init__(
|
1089 |
+
self,
|
1090 |
+
num_warmup_steps=40,
|
1091 |
+
is_enabled: bool = False,
|
1092 |
+
model_name: str = "mistral",
|
1093 |
+
test_dataset: Dataset = None,
|
1094 |
+
targeted_sparsity: float = 0.5,
|
1095 |
+
keep_regularization_with_kill: bool = False,
|
1096 |
+
):
|
1097 |
+
"""Scheduler for regularizing the model first before applying the dead threshold.
|
1098 |
+
|
1099 |
+
:param num_warmup_steps: number of training steps required to reach the dead threshold, defaults to 40
|
1100 |
+
:param increment_ratio: by how much to increase the dead threshold.
|
1101 |
+
For example, 0.5 means "increase the threshold by 0.5 * desired threshold
|
1102 |
+
"""
|
1103 |
+
self.num_warmup_steps = num_warmup_steps
|
1104 |
+
self.is_enabled = is_enabled
|
1105 |
+
self.model_name = model_name
|
1106 |
+
self.test_dataset = test_dataset
|
1107 |
+
self.targeted_sparsity = targeted_sparsity
|
1108 |
+
self.keep_regularization_with_kill = keep_regularization_with_kill
|
1109 |
+
self.act_hist_path = (
|
1110 |
+
f"/matx/u/vxbrando/histograms/warm_up_reg_{targeted_sparsity}/act_hist.pt"
|
1111 |
+
)
|
1112 |
+
if self.is_enabled:
|
1113 |
+
print("GracefulRegularizationScheduler is enabled.")
|
1114 |
+
self.trainer = None
|
1115 |
+
|
1116 |
+
def set_trainer(self, trainer):
|
1117 |
+
self.trainer = trainer
|
1118 |
+
|
1119 |
+
def on_step_end(self, args, state, control, **kwargs):
|
1120 |
+
if not self.is_enabled:
|
1121 |
+
return
|
1122 |
+
|
1123 |
+
model = kwargs["model"]
|
1124 |
+
if isinstance(model, PeftModel):
|
1125 |
+
base_model = model.get_base_model()
|
1126 |
+
else:
|
1127 |
+
base_model = model
|
1128 |
+
|
1129 |
+
if state.global_step == 1:
|
1130 |
+
ds_print("Setting an initial reg threshold to 0.1")
|
1131 |
+
set_regularization_threshold(base_model, 0.1)
|
1132 |
+
|
1133 |
+
# if state.global_step >= self.num_warmup_steps and state.global_step % 50 == 0:
|
1134 |
+
if state.global_step == self.num_warmup_steps:
|
1135 |
+
activate_stats(base_model)
|
1136 |
+
enable_sparse_silu(base_model)
|
1137 |
+
self.trainer.evaluate()
|
1138 |
+
save_act_hist(base_model, self.act_hist_path)
|
1139 |
+
set_sparse_threshold(base_model, self.targeted_sparsity, True)
|
1140 |
+
deactivate_stats(base_model)
|
1141 |
+
self.trainer.use_sparse_regularization = self.keep_regularization_with_kill
|
1142 |
+
# set_layer_specific_regularization(model.get_base_model())
|
1143 |
+
print_dead_neuron_stats(model.get_base_model())
|
1144 |
+
|
1145 |
+
if state.global_step % 2000 == 0:
|
1146 |
+
if is_mainprocess():
|
1147 |
+
ds_print(
|
1148 |
+
f"Saving to /scr/lukeai/{self.model_name}_{state.global_step}.pt",
|
1149 |
+
)
|
1150 |
+
torch.save(
|
1151 |
+
model.state_dict(),
|
1152 |
+
f"/scr/lukeai/{self.model_name}_{state.global_step}.pt",
|
1153 |
+
)
|
1154 |
+
|
1155 |
+
|
1156 |
+
class GradualSparsificationScheduler(TrainerCallback):
|
1157 |
+
def __init__(
|
1158 |
+
self,
|
1159 |
+
num_warmup_steps=40,
|
1160 |
+
increment_ratio=0.5,
|
1161 |
+
is_enabled: bool = False,
|
1162 |
+
model_name: str = "mistral",
|
1163 |
+
):
|
1164 |
+
"""Scheduler for gradually increasing a dead threshold until it reaches the desired threshold.
|
1165 |
+
|
1166 |
+
:param num_warmup_steps: number of training steps required to reach the dead threshold, defaults to 40
|
1167 |
+
:param increment_ratio: by how much to increase the dead threshold.
|
1168 |
+
For example, 0.5 means "increase the threshold by 0.5 * desired threshold
|
1169 |
+
"""
|
1170 |
+
self.num_warmup_steps = num_warmup_steps
|
1171 |
+
self.increment_ratio = increment_ratio
|
1172 |
+
self.step_size = int(num_warmup_steps * increment_ratio)
|
1173 |
+
self.is_enabled = is_enabled
|
1174 |
+
self.model_name = model_name
|
1175 |
+
|
1176 |
+
def on_step_end(self, args, state, control, **kwargs):
|
1177 |
+
model = kwargs["model"]
|
1178 |
+
|
1179 |
+
if not self.is_enabled:
|
1180 |
+
if state.global_step <= 10:
|
1181 |
+
for module in model.modules():
|
1182 |
+
if isinstance(module, MistralSparseSiluMLP):
|
1183 |
+
module.current_dead_threshold = module.dead_threshold
|
1184 |
+
return
|
1185 |
+
|
1186 |
+
current_dead_threshold = 0
|
1187 |
+
desired_dead_threshold = 0
|
1188 |
+
|
1189 |
+
if is_mainprocess():
|
1190 |
+
ds_print(state.global_step)
|
1191 |
+
|
1192 |
+
if state.global_step % self.step_size == 2:
|
1193 |
+
for module in model.modules():
|
1194 |
+
if isinstance(module, MistralSparseSiluMLP):
|
1195 |
+
desired_dead_threshold = copy.deepcopy(module.dead_threshold)
|
1196 |
+
current_dead_threshold = module.current_dead_threshold
|
1197 |
+
current_dead_threshold += (
|
1198 |
+
self.increment_ratio * desired_dead_threshold
|
1199 |
+
)
|
1200 |
+
module.current_dead_threshold = min(
|
1201 |
+
desired_dead_threshold, current_dead_threshold
|
1202 |
+
)
|
1203 |
+
|
1204 |
+
if is_running_deepspeed and is_mainprocess():
|
1205 |
+
ds_print(
|
1206 |
+
state.global_step,
|
1207 |
+
current_dead_threshold,
|
1208 |
+
desired_dead_threshold,
|
1209 |
+
)
|
1210 |
+
|
1211 |
+
if state.global_step % 2000 == 0:
|
1212 |
+
if is_running_deepspeed and is_mainprocess():
|
1213 |
+
ds_print(
|
1214 |
+
f"Saving to /matx/u/lukeai/{self.model_name}_{state.global_step - 2}.pt",
|
1215 |
+
)
|
1216 |
+
torch.save(
|
1217 |
+
model.state_dict(),
|
1218 |
+
f"/matx/u/lukeai/{self.model_name}_{state.global_step - 2}.pt",
|
1219 |
+
)
|
1220 |
+
|
1221 |
+
|
1222 |
+
def get_sparse_mistral_config(
|
1223 |
+
config: MistralConfig,
|
1224 |
+
use_sparse_model=False,
|
1225 |
+
use_sparse_predictor=False,
|
1226 |
+
use_sparse_regularization=False,
|
1227 |
+
thresholds=None,
|
1228 |
+
):
|
1229 |
+
new_config = SparseMistralConfig()
|
1230 |
+
new_config.__dict__.update(config.__dict__)
|
1231 |
+
config = new_config
|
1232 |
+
config.use_sparse_model = use_sparse_model
|
1233 |
+
config.use_sparse_predictor = use_sparse_predictor
|
1234 |
+
config.use_sparse_regularization = use_sparse_regularization
|
1235 |
+
config.thresholds = thresholds
|
1236 |
+
|
1237 |
+
return config
|
1238 |
+
|
1239 |
+
|
1240 |
+
def apply_mistral_sparse_silu_mlp(
|
1241 |
+
model,
|
1242 |
+
config,
|
1243 |
+
use_sparse_regularization: bool = False,
|
1244 |
+
):
|
1245 |
+
# counts = 0
|
1246 |
+
for layer in model.model.layers:
|
1247 |
+
# counts += 1
|
1248 |
+
# if counts < 4:
|
1249 |
+
# continue
|
1250 |
+
original_mlp = layer.mlp
|
1251 |
+
new_mlp = MistralSparseSiluMLP(
|
1252 |
+
config, use_sparse_regularization=use_sparse_regularization
|
1253 |
+
)
|
1254 |
+
new_mlp.gate_proj = original_mlp.gate_proj
|
1255 |
+
new_mlp.up_proj = original_mlp.up_proj
|
1256 |
+
new_mlp.down_proj = original_mlp.down_proj
|
1257 |
+
layer.mlp = new_mlp
|
1258 |
+
|
1259 |
+
# for layer in model.model.layers:
|
1260 |
+
# original_attention = layer.self_attn
|
1261 |
+
# new_attention = SparseMistralAttention(
|
1262 |
+
# config=original_attention.config, layer_idx=original_attention.layer_idx
|
1263 |
+
# )
|
1264 |
+
# for attr in vars(original_attention):
|
1265 |
+
# setattr(new_attention, attr, getattr(original_attention, attr))
|
1266 |
+
# layer.self_attn = new_attention
|
1267 |
+
|
1268 |
+
|
1269 |
+
def apply_mistral_sparse_attention(
|
1270 |
+
model,
|
1271 |
+
config,
|
1272 |
+
):
|
1273 |
+
for layer in model.model.layers:
|
1274 |
+
layer.self_attention = layer.self_attention
|
1275 |
+
|
1276 |
+
|
1277 |
+
def apply_mistral_sparse_decoder_layer(
|
1278 |
+
model,
|
1279 |
+
config,
|
1280 |
+
init_svd: bool = True,
|
1281 |
+
):
|
1282 |
+
assert isinstance(model.model, MistralModel), "model.model must be a MistralModel."
|
1283 |
+
new_layers = []
|
1284 |
+
for layer_idx, layer in enumerate(model.model.layers):
|
1285 |
+
if isinstance(layer.mlp, MistralSparseSiluMLP):
|
1286 |
+
new_layers.append(
|
1287 |
+
SparseMistralDecoderLayer(
|
1288 |
+
config=config,
|
1289 |
+
layer_idx=layer_idx,
|
1290 |
+
decoder_layer=layer,
|
1291 |
+
init_svd=init_svd,
|
1292 |
+
)
|
1293 |
+
)
|
1294 |
+
print(f"{layer_idx}th mlp layer activation: {layer.mlp.sparse_act_fn}")
|
1295 |
+
else:
|
1296 |
+
new_layers.append(layer)
|
1297 |
+
model.model.layers = nn.ModuleList(new_layers)
|
1298 |
+
|
1299 |
+
|
1300 |
+
def enable_sparse_predictor(
|
1301 |
+
model,
|
1302 |
+
):
|
1303 |
+
for layer_idx, layer in enumerate(model.model.layers):
|
1304 |
+
if isinstance(layer, MistralDecoderLayer):
|
1305 |
+
layer.use_sparse_predictor = True
|
1306 |
+
|
1307 |
+
|
1308 |
+
def disable_sparse_predictor(
|
1309 |
+
model,
|
1310 |
+
):
|
1311 |
+
for layer_idx, layer in enumerate(model.model.layers):
|
1312 |
+
if isinstance(layer, MistralDecoderLayer):
|
1313 |
+
layer.use_sparse_predictor = False
|
1314 |
+
|
1315 |
+
|
1316 |
+
def activate_stats(model, is_collect_histogram: bool = True):
|
1317 |
+
for layer in model.model.layers:
|
1318 |
+
if isinstance(layer.mlp, MistralSparseSiluMLP):
|
1319 |
+
layer.mlp.activate_stats(is_collect_histogram=is_collect_histogram)
|
1320 |
+
|
1321 |
+
|
1322 |
+
def deactivate_stats(model):
|
1323 |
+
for layer in model.model.layers:
|
1324 |
+
if isinstance(layer.mlp, MistralSparseSiluMLP):
|
1325 |
+
layer.mlp.deactivate_stats()
|
1326 |
+
|
1327 |
+
|
1328 |
+
def enable_sparse_silu(model):
|
1329 |
+
print("Enabling SparseSilu")
|
1330 |
+
for i, layer in enumerate(model.model.layers):
|
1331 |
+
if isinstance(layer.mlp, MistralSparseSiluMLP):
|
1332 |
+
layer.mlp.kill_sparse_swish_outputs = True
|
1333 |
+
|
1334 |
+
|
1335 |
+
def print_dead_neuron_stats(model):
|
1336 |
+
total_sparsity = 0
|
1337 |
+
counts = 0
|
1338 |
+
for i, layer in enumerate(model.model.layers):
|
1339 |
+
if isinstance(layer.mlp, MistralSparseSiluMLP):
|
1340 |
+
dead_percentage = layer.mlp.dead_percentage * 100
|
1341 |
+
agg_sparsity = layer.mlp.agg_sparsity * 100
|
1342 |
+
print(f"layer {i} sparsity: {dead_percentage:.3f}%")
|
1343 |
+
print(f"layer {i} agg sparsity: {agg_sparsity:.3f}%")
|
1344 |
+
total_sparsity += dead_percentage
|
1345 |
+
counts += 1
|
1346 |
+
|
1347 |
+
print(f"Total sparsity: {total_sparsity/counts: .3f}%")
|
1348 |
+
return total_sparsity / counts
|
1349 |
+
|
1350 |
+
|
1351 |
+
def get_sparse_layers(model: MistralModel):
|
1352 |
+
sparse_layers = [
|
1353 |
+
m.mlp for m in model.layers() if isinstance(m.mlp, MistralSparseSiluMLP)
|
1354 |
+
]
|
1355 |
+
return sparse_layers
|
1356 |
+
|
1357 |
+
|
1358 |
+
def get_threshold(
|
1359 |
+
bin_edges: torch.tensor, histogram_counts: torch.tensor, sparsity_level: float
|
1360 |
+
): # Only for L1 Regularization
|
1361 |
+
assert (
|
1362 |
+
len(bin_edges.shape) == len(histogram_counts.shape) == 1
|
1363 |
+
), "bin_edges and histogram are expected to be 1-dimensional."
|
1364 |
+
histogram_counts /= histogram_counts.sum()
|
1365 |
+
threshold_idx = torch.searchsorted(
|
1366 |
+
histogram_counts.cumsum(0), sparsity_level, side="right"
|
1367 |
+
)
|
1368 |
+
|
1369 |
+
return bin_edges[threshold_idx]
|
1370 |
+
|
1371 |
+
|
1372 |
+
def set_regularization_threshold(model, threshold: float = 0.1):
|
1373 |
+
for i, layer in enumerate(model.model.layers):
|
1374 |
+
if (
|
1375 |
+
isinstance(layer.mlp, MistralSparseSiluMLP) and layer.mlp.is_stats
|
1376 |
+
): # Can set the threshold only the relevant statistics is collected.
|
1377 |
+
layer.mlp.regularization_threshold = threshold # TODO: find better param
|
1378 |
+
|
1379 |
+
|
1380 |
+
def set_sparse_threshold(
|
1381 |
+
model, sparsity_level: float, use_relu: bool = False, use_resilu: bool = False
|
1382 |
+
):
|
1383 |
+
assert not (use_relu and use_resilu), "It's not allowed to use both relu and resilu"
|
1384 |
+
for i, layer in enumerate(model.model.layers):
|
1385 |
+
if (
|
1386 |
+
isinstance(layer.mlp, MistralSparseSiluMLP) and layer.mlp.is_stats
|
1387 |
+
): # Can set the threshold only the relevant statistics is collected.
|
1388 |
+
if use_relu:
|
1389 |
+
layer.mlp.sparse_act_fn = nn.ReLU()
|
1390 |
+
layer.mlp.use_relu = True
|
1391 |
+
layer.mlp.use_resilu = False
|
1392 |
+
elif use_resilu:
|
1393 |
+
layer.mlp.sparse_act_fn = nn.Sequential(nn.ReLU(), nn.SiLU())
|
1394 |
+
layer.mlp.use_resilu = True
|
1395 |
+
layer.mlp.use_relu = False
|
1396 |
+
else:
|
1397 |
+
layer.mlp.dead_threshold = get_threshold(
|
1398 |
+
layer.mlp.histogram_bins,
|
1399 |
+
layer.mlp.post_act_hist_counts,
|
1400 |
+
sparsity_level,
|
1401 |
+
)
|
1402 |
+
layer.mlp.sparse_act_fn.set_new_threshold(layer.mlp.dead_threshold)
|
1403 |
+
layer.mlp.regularization_threshold = (
|
1404 |
+
layer.mlp.dead_threshold * 1.2
|
1405 |
+
) # TODO: find better param
|
1406 |
+
|
1407 |
+
|
1408 |
+
def plot_histogram(
|
1409 |
+
bin_edges,
|
1410 |
+
histogram_counts: torch.tensor,
|
1411 |
+
title: str = "Activation Distribution",
|
1412 |
+
fig_dir: str = "figures",
|
1413 |
+
):
|
1414 |
+
plt.bar(
|
1415 |
+
bin_edges[:-1], histogram_counts, width=np.diff(bin_edges), edgecolor="black"
|
1416 |
+
)
|
1417 |
+
plt.title(title)
|
1418 |
+
plt.xlabel("Activation Value")
|
1419 |
+
plt.ylabel("Frequency")
|
1420 |
+
os.makedirs(fig_dir, exist_ok=True)
|
1421 |
+
plt.savefig(f"{fig_dir}/{title}.png")
|
1422 |
+
# plt.show()
|
1423 |
+
plt.clf()
|
1424 |
+
|
1425 |
+
|
1426 |
+
def plot_act(model, fig_dir: str = "figures"):
|
1427 |
+
for i, layer in enumerate(model.model.layers):
|
1428 |
+
if (
|
1429 |
+
isinstance(layer.mlp, MistralSparseSiluMLP) and layer.mlp.is_stats
|
1430 |
+
): # Can set the threshold only the relevant statistics is collected.
|
1431 |
+
plot_title = f"Layer: {i} Pre-Activation Distribution"
|
1432 |
+
plot_histogram(
|
1433 |
+
layer.mlp.histogram_bins, layer.mlp.pre_act_hist_counts, plot_title
|
1434 |
+
)
|
1435 |
+
|
1436 |
+
plot_title = f"Layer: {i} Post-Activation Absolute Distribution"
|
1437 |
+
plot_histogram(
|
1438 |
+
layer.mlp.histogram_bins, layer.mlp.post_act_hist_counts, plot_title
|
1439 |
+
)
|
1440 |
+
|
1441 |
+
|
1442 |
+
def save_act_hist(
|
1443 |
+
model, filename="/scr/jay/models/mistral/pre_finetune/cola_act_hist.pt"
|
1444 |
+
):
|
1445 |
+
os.makedirs(os.path.dirname(filename), exist_ok=True)
|
1446 |
+
act_dict = {}
|
1447 |
+
for i, layer in enumerate(model.model.layers):
|
1448 |
+
if (
|
1449 |
+
isinstance(layer.mlp, MistralSparseSiluMLP) and layer.mlp.is_stats
|
1450 |
+
): # Can set the threshold only the relevant statistics is collected.
|
1451 |
+
act_dict[i] = (
|
1452 |
+
layer.mlp.histogram_bins,
|
1453 |
+
# layer.mlp.pre_mlp_hist_counts,
|
1454 |
+
layer.mlp.pre_act_hist_counts,
|
1455 |
+
layer.mlp.post_act_hist_counts,
|
1456 |
+
)
|
1457 |
+
print("Saving activation histograms...\n\n\n")
|
1458 |
+
torch.save(act_dict, filename)
|
1459 |
+
|
1460 |
+
|
1461 |
+
def load_act_hist(
|
1462 |
+
model, filename="/scr/jay/models/mistral/pre_finetune/cola_act_hist.pt"
|
1463 |
+
):
|
1464 |
+
assert os.path.exists(
|
1465 |
+
filename
|
1466 |
+
), f"{filename} does not exist when loading pre/post-activation histogram of SparseMistralSiluMLP."
|
1467 |
+
print("Loading activation histograms...\n\n\n")
|
1468 |
+
|
1469 |
+
act_dict = torch.load(filename)
|
1470 |
+
for i, layer in enumerate(model.model.layers):
|
1471 |
+
if (
|
1472 |
+
isinstance(layer.mlp, MistralSparseSiluMLP) and layer.mlp.is_stats
|
1473 |
+
): # Can set the threshold only the relevant statistics is collected.
|
1474 |
+
(
|
1475 |
+
layer.mlp.histogram_bins,
|
1476 |
+
# layer.mlp.pre_mlp_hist_counts,
|
1477 |
+
layer.mlp.pre_act_hist_counts,
|
1478 |
+
layer.mlp.post_act_hist_counts,
|
1479 |
+
) = act_dict[i]
|
1480 |
+
|
1481 |
+
|
1482 |
+
def enable_last_k_modules(model, start_module_idx: int):
|
1483 |
+
assert 32 > start_module_idx >= 0
|
1484 |
+
new_modules = []
|
1485 |
+
new_idx = 0
|
1486 |
+
for idx in range(start_module_idx, len(model.model.original_layers)):
|
1487 |
+
module = model.model.original_layers[idx]
|
1488 |
+
module.layer_idx = new_idx
|
1489 |
+
module.self_attn.layer_idx = new_idx
|
1490 |
+
new_modules.append(module)
|
1491 |
+
new_idx += 1
|
1492 |
+
print(module.layer_idx)
|
1493 |
+
|
1494 |
+
model.model.layers = nn.ModuleList(new_modules)
|
1495 |
+
|
1496 |
+
|
1497 |
+
def enable_first_k_modules(model, end_module_idx: int):
|
1498 |
+
assert 32 > end_module_idx >= 0
|
1499 |
+
new_modules = []
|
1500 |
+
new_idx = 0
|
1501 |
+
for idx in range(0, end_module_idx + 1):
|
1502 |
+
module = model.model.original_layers[idx]
|
1503 |
+
module.layer_idx = new_idx
|
1504 |
+
module.self_attn.layer_idx = new_idx
|
1505 |
+
new_modules.append(module)
|
1506 |
+
new_idx += 1
|
1507 |
+
print(module.layer_idx)
|
1508 |
+
|
1509 |
+
model.model.layers = nn.ModuleList(new_modules)
|