vxbrandon commited on
Commit
b83afa8
1 Parent(s): ac075fa

End of training

Browse files
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_50pcut_pre_mlpcut_pre_attn_2024-03-22
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_50pcut_pre_mlpcut_pre_attn_2024-03-22
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: 2.3247
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,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "cut_pre_attn": true,
13
+ "cut_pre_mlp": true,
14
+ "eos_token_id": 2,
15
+ "hidden_act": "silu",
16
+ "hidden_size": 4096,
17
+ "initializer_range": 0.02,
18
+ "intermediate_size": 14336,
19
+ "max_position_embeddings": 32768,
20
+ "model_type": "sparse_mistral",
21
+ "num_attention_heads": 32,
22
+ "num_hidden_layers": 32,
23
+ "num_key_value_heads": 8,
24
+ "pre_attn_thresholds": [
25
+ 0.0,
26
+ 0.0,
27
+ 0.0,
28
+ 0.0,
29
+ 0.0,
30
+ 0.0,
31
+ 0.0,
32
+ 0.0,
33
+ 0.0,
34
+ 0.0,
35
+ 0.0,
36
+ 0.0,
37
+ 0.0,
38
+ 0.0,
39
+ 0.0,
40
+ 0.0,
41
+ 0.0,
42
+ 0.0,
43
+ 0.0,
44
+ 0.0,
45
+ 0.0,
46
+ 0.0,
47
+ 0.0,
48
+ 0.0,
49
+ 0.0,
50
+ 0.0,
51
+ 0.0,
52
+ 0.0,
53
+ 0.0,
54
+ 0.0,
55
+ 0.0,
56
+ 0.0
57
+ ],
58
+ "pre_mlp_thresholds": [
59
+ 0.0,
60
+ 0.0,
61
+ 0.0,
62
+ 0.0,
63
+ 0.0,
64
+ 0.0,
65
+ 0.0,
66
+ 0.0,
67
+ 0.0,
68
+ 0.0,
69
+ 0.0,
70
+ 0.0,
71
+ 0.0,
72
+ 0.0,
73
+ 0.0,
74
+ 0.0,
75
+ 0.0,
76
+ 0.0,
77
+ 0.0,
78
+ 0.0,
79
+ 0.0,
80
+ 0.0,
81
+ 0.0,
82
+ 0.0,
83
+ 0.0,
84
+ 0.0,
85
+ 0.0,
86
+ 0.0,
87
+ 0.0,
88
+ 0.0,
89
+ 0.0,
90
+ 0.0
91
+ ],
92
+ "rms_norm_eps": 1e-05,
93
+ "rope_theta": 10000.0,
94
+ "sliding_window": 4096,
95
+ "thresholds": [
96
+ 0.017051145434379578,
97
+ 0.023069201037287712,
98
+ 0.049147434532642365,
99
+ 0.051153454929590225,
100
+ 0.061183542013168335,
101
+ 0.07121363282203674,
102
+ 0.0732196494936943,
103
+ 0.07923770695924759,
104
+ 0.08324974030256271,
105
+ 0.08124372363090515,
106
+ 0.089267797768116,
107
+ 0.09127381443977356,
108
+ 0.10130390524864197,
109
+ 0.0992978885769844,
110
+ 0.10732196271419525,
111
+ 0.12337010353803635,
112
+ 0.14343027770519257,
113
+ 0.16148445010185242,
114
+ 0.17953860759735107,
115
+ 0.1935807317495346,
116
+ 0.1995987892150879,
117
+ 0.2196589708328247,
118
+ 0.2196589708328247,
119
+ 0.23169508576393127,
120
+ 0.2357071191072464,
121
+ 0.23370109498500824,
122
+ 0.225677028298378,
123
+ 0.22968906164169312,
124
+ 0.225677028298378,
125
+ 0.22768303751945496,
126
+ 0.2457372099161148,
127
+ 0.2678034007549286
128
+ ],
129
+ "tie_word_embeddings": false,
130
+ "torch_dtype": "bfloat16",
131
+ "transformers_version": "4.36.2",
132
+ "use_cache": false,
133
+ "use_relu": false,
134
+ "use_resilu": false,
135
+ "use_sparse_model": true,
136
+ "use_sparse_predictor": false,
137
+ "use_sparse_regularization": false,
138
+ "vocab_size": 32000
139
+ }
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:dea99da8657d147ecc50aec031ab203345be66e1ec4839d8a5d52fa25598bf9e
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:ed0d5a12d4281ee3b3c1f3b54fb2e8ba41200b2a953f8020dffb9c6dc997abff
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:ab26f8b3d61c4d5297facdc668eadbea62b58ac01120ae9e65344aa35a59b2b9
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,1623 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 SparseMistralFlashAttention(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
+ self.pre_attn_sparsity = 0
369
+ self.visit_counts = 0
370
+ self.is_stats = False
371
+ self.pre_attn_std = 0
372
+ self.pre_attn_threshold = 0
373
+
374
+ def activate_stats(self):
375
+ self.is_stats = True
376
+ self.visit_counts = 0
377
+ self.pre_attn_sparsity = 0
378
+ self.pre_attn_std = 0
379
+
380
+ def deactivate_stats(self):
381
+ self.is_stats = False
382
+
383
+ def forward(
384
+ self,
385
+ hidden_states: torch.Tensor,
386
+ attention_mask: Optional[torch.Tensor] = None,
387
+ position_ids: Optional[torch.LongTensor] = None,
388
+ past_key_value: Optional = None,
389
+ output_attentions: bool = False,
390
+ use_cache: bool = False,
391
+ **kwargs,
392
+ ):
393
+ if "padding_mask" in kwargs:
394
+ warnings.warn(
395
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
396
+ )
397
+
398
+ # overwrite attention_mask with padding_mask
399
+ attention_mask = kwargs.pop("padding_mask")
400
+ bsz, q_len, _ = hidden_states.size()
401
+ mask = abs(hidden_states - hidden_states.mean()) < self.pre_attn_threshold
402
+ hidden_states[mask] = 0
403
+ self.counts += 1
404
+
405
+ if self.is_stats:
406
+ self.pre_attn_sparsity = (
407
+ self.pre_attn_sparsity * self.visit_counts
408
+ + (hidden_states == 0).float().mean()
409
+ ) / (self.visit_counts + 1)
410
+ self.pre_attn_std = (
411
+ self.pre_attn_std * self.visit_counts + 0.6 * hidden_states.std()
412
+ ) / (self.visit_counts + 1)
413
+ self.visit_counts += 1
414
+ self.counts -= 1
415
+
416
+ if self.counts == 10:
417
+ print(f"Attention {self.layer_idx}: ", (hidden_states == 0).float().mean())
418
+ print(
419
+ mask.shape,
420
+ )
421
+
422
+ query_states = self.q_proj(hidden_states)
423
+ key_states = self.k_proj(hidden_states)
424
+ value_states = self.v_proj(hidden_states)
425
+
426
+ query_states = query_states.view(
427
+ bsz, q_len, self.num_heads, self.head_dim
428
+ ).transpose(1, 2)
429
+ key_states = key_states.view(
430
+ bsz, q_len, self.num_key_value_heads, self.head_dim
431
+ ).transpose(1, 2)
432
+ value_states = value_states.view(
433
+ bsz, q_len, self.num_key_value_heads, self.head_dim
434
+ ).transpose(1, 2)
435
+
436
+ kv_seq_len = key_states.shape[-2]
437
+ if past_key_value is not None:
438
+ if self.layer_idx is None:
439
+ raise ValueError(
440
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
441
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
442
+ "with a layer index."
443
+ )
444
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
445
+
446
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
447
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
448
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
449
+
450
+ query_states, key_states = apply_rotary_pos_emb(
451
+ query_states, key_states, cos, sin, position_ids
452
+ )
453
+
454
+ use_sliding_windows = (
455
+ _flash_supports_window_size
456
+ and getattr(self.config, "sliding_window", None) is not None
457
+ and kv_seq_len > self.config.sliding_window
458
+ )
459
+
460
+ if not _flash_supports_window_size:
461
+ logger.warning_once(
462
+ "The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
463
+ " make sure to upgrade flash-attn library."
464
+ )
465
+
466
+ if past_key_value is not None:
467
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
468
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
469
+ if (
470
+ getattr(self.config, "sliding_window", None) is not None
471
+ and kv_seq_len > self.config.sliding_window
472
+ and cache_has_contents
473
+ ):
474
+ slicing_tokens = 1 - self.config.sliding_window
475
+
476
+ past_key = past_key_value[self.layer_idx][0]
477
+ past_value = past_key_value[self.layer_idx][1]
478
+
479
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
480
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
481
+
482
+ if past_key.shape[-2] != self.config.sliding_window - 1:
483
+ raise ValueError(
484
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
485
+ f" {past_key.shape}"
486
+ )
487
+
488
+ if attention_mask is not None:
489
+ attention_mask = attention_mask[:, slicing_tokens:]
490
+ attention_mask = torch.cat(
491
+ [attention_mask, torch.ones_like(attention_mask[:, -1:])],
492
+ dim=-1,
493
+ )
494
+
495
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
496
+ key_states, value_states = past_key_value.update(
497
+ key_states, value_states, self.layer_idx, cache_kwargs
498
+ )
499
+
500
+ # repeat k/v heads if n_kv_heads < n_heads
501
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
502
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
503
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
504
+
505
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
506
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
507
+ # cast them back in float16 just to be sure everything works as expected.
508
+ input_dtype = query_states.dtype
509
+ if input_dtype == torch.float32:
510
+ if torch.is_autocast_enabled():
511
+ target_dtype = torch.get_autocast_gpu_dtype()
512
+ # Handle the case where the model is quantized
513
+ elif hasattr(self.config, "_pre_quantization_dtype"):
514
+ target_dtype = self.config._pre_quantization_dtype
515
+ else:
516
+ target_dtype = self.q_proj.weight.dtype
517
+
518
+ logger.warning_once(
519
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
520
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
521
+ f" {target_dtype}."
522
+ )
523
+
524
+ query_states = query_states.to(target_dtype)
525
+ key_states = key_states.to(target_dtype)
526
+ value_states = value_states.to(target_dtype)
527
+
528
+ # Reashape to the expected shape for Flash Attention
529
+ query_states = query_states.transpose(1, 2)
530
+ key_states = key_states.transpose(1, 2)
531
+ value_states = value_states.transpose(1, 2)
532
+
533
+ attn_output = self._flash_attention_forward(
534
+ query_states,
535
+ key_states,
536
+ value_states,
537
+ attention_mask,
538
+ q_len,
539
+ dropout=dropout_rate,
540
+ use_sliding_windows=use_sliding_windows,
541
+ )
542
+
543
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
544
+ attn_output = self.o_proj(attn_output)
545
+
546
+ if not output_attentions:
547
+ attn_weights = None
548
+
549
+ return attn_output, attn_weights, past_key_value
550
+
551
+ def _flash_attention_forward(
552
+ self,
553
+ query_states,
554
+ key_states,
555
+ value_states,
556
+ attention_mask,
557
+ query_length,
558
+ dropout=0.0,
559
+ softmax_scale=None,
560
+ use_sliding_windows=False,
561
+ ):
562
+ """
563
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
564
+ first unpad the input, then computes the attention scores and pad the final attention scores.
565
+
566
+ Args:
567
+ query_states (`torch.Tensor`):
568
+ Input query states to be passed to Flash Attention API
569
+ key_states (`torch.Tensor`):
570
+ Input key states to be passed to Flash Attention API
571
+ value_states (`torch.Tensor`):
572
+ Input value states to be passed to Flash Attention API
573
+ attention_mask (`torch.Tensor`):
574
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
575
+ position of padding tokens and 1 for the position of non-padding tokens.
576
+ dropout (`float`):
577
+ Attention dropout
578
+ softmax_scale (`float`, *optional*):
579
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
580
+ use_sliding_windows (`bool`, *optional*):
581
+ Whether to activate sliding window attention.
582
+ """
583
+ if not self._flash_attn_uses_top_left_mask:
584
+ causal = self.is_causal
585
+ else:
586
+ # 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__.
587
+ causal = self.is_causal and query_length != 1
588
+
589
+ # Contains at least one padding token in the sequence
590
+ if attention_mask is not None:
591
+ batch_size = query_states.shape[0]
592
+ (
593
+ query_states,
594
+ key_states,
595
+ value_states,
596
+ indices_q,
597
+ cu_seq_lens,
598
+ max_seq_lens,
599
+ ) = self._upad_input(
600
+ query_states, key_states, value_states, attention_mask, query_length
601
+ )
602
+
603
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
604
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
605
+
606
+ if not use_sliding_windows:
607
+ attn_output_unpad = flash_attn_varlen_func(
608
+ query_states,
609
+ key_states,
610
+ value_states,
611
+ cu_seqlens_q=cu_seqlens_q,
612
+ cu_seqlens_k=cu_seqlens_k,
613
+ max_seqlen_q=max_seqlen_in_batch_q,
614
+ max_seqlen_k=max_seqlen_in_batch_k,
615
+ dropout_p=dropout,
616
+ softmax_scale=softmax_scale,
617
+ causal=causal,
618
+ )
619
+ else:
620
+ attn_output_unpad = flash_attn_varlen_func(
621
+ query_states,
622
+ key_states,
623
+ value_states,
624
+ cu_seqlens_q=cu_seqlens_q,
625
+ cu_seqlens_k=cu_seqlens_k,
626
+ max_seqlen_q=max_seqlen_in_batch_q,
627
+ max_seqlen_k=max_seqlen_in_batch_k,
628
+ dropout_p=dropout,
629
+ softmax_scale=softmax_scale,
630
+ causal=causal,
631
+ window_size=(
632
+ self.config.sliding_window,
633
+ self.config.sliding_window,
634
+ ),
635
+ )
636
+
637
+ attn_output = pad_input(
638
+ attn_output_unpad, indices_q, batch_size, query_length
639
+ )
640
+ else:
641
+ if not use_sliding_windows:
642
+ attn_output = flash_attn_func(
643
+ query_states,
644
+ key_states,
645
+ value_states,
646
+ dropout,
647
+ softmax_scale=softmax_scale,
648
+ causal=causal,
649
+ )
650
+ else:
651
+ attn_output = flash_attn_func(
652
+ query_states,
653
+ key_states,
654
+ value_states,
655
+ dropout,
656
+ softmax_scale=softmax_scale,
657
+ causal=causal,
658
+ window_size=(
659
+ self.config.sliding_window,
660
+ self.config.sliding_window,
661
+ ),
662
+ )
663
+
664
+ return attn_output
665
+
666
+ def _upad_input(
667
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
668
+ ):
669
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
670
+
671
+ # On the first iteration we need to properly re-create the padding mask
672
+ # by slicing it on the proper place
673
+ if kv_seq_len != attention_mask.shape[-1]:
674
+ attention_mask_num_tokens = attention_mask.shape[-1]
675
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
676
+
677
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
678
+
679
+ key_layer = index_first_axis(
680
+ key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
681
+ )
682
+ value_layer = index_first_axis(
683
+ value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
684
+ )
685
+
686
+ if query_length == kv_seq_len:
687
+ query_layer = index_first_axis(
688
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim),
689
+ indices_k,
690
+ )
691
+ cu_seqlens_q = cu_seqlens_k
692
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
693
+ indices_q = indices_k
694
+ elif query_length == 1:
695
+ max_seqlen_in_batch_q = 1
696
+ cu_seqlens_q = torch.arange(
697
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
698
+ ) # There is a memcpy here, that is very bad.
699
+ indices_q = cu_seqlens_q[:-1]
700
+ query_layer = query_layer.squeeze(1)
701
+ else:
702
+ # The -q_len: slice assumes left padding.
703
+ attention_mask = attention_mask[:, -query_length:]
704
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
705
+ query_layer, attention_mask
706
+ )
707
+
708
+ return (
709
+ query_layer,
710
+ key_layer,
711
+ value_layer,
712
+ indices_q,
713
+ (cu_seqlens_q, cu_seqlens_k),
714
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
715
+ )
716
+
717
+
718
+ class SparseMistralAttention(MistralAttention):
719
+ def __init__(self, *args, **kwargs):
720
+ super().__init__(*args, **kwargs)
721
+
722
+ self.counts = 0
723
+
724
+ def forward(
725
+ self,
726
+ hidden_states: torch.Tensor,
727
+ attention_mask: Optional[torch.Tensor] = None,
728
+ position_ids: Optional[torch.LongTensor] = None,
729
+ past_key_value: Optional = None,
730
+ output_attentions: bool = False,
731
+ use_cache: bool = False,
732
+ **kwargs,
733
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
734
+ if "padding_mask" in kwargs:
735
+ warnings.warn(
736
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
737
+ )
738
+ bsz, q_len, _ = hidden_states.size()
739
+ mask = abs(hidden_states - hidden_states.mean()) < 0.6 * hidden_states.std()
740
+ hidden_states[mask] = 0
741
+ self.counts += 1
742
+ if 10 <= self.counts <= 11:
743
+ print(f"Attention {self.layer_idx}: ", (hidden_states == 0).float().mean())
744
+ self.counts += 1
745
+
746
+ query_states = self.q_proj(hidden_states)
747
+ key_states = self.k_proj(hidden_states)
748
+ value_states = self.v_proj(hidden_states)
749
+
750
+ query_states = query_states.view(
751
+ bsz, q_len, self.num_heads, self.head_dim
752
+ ).transpose(1, 2)
753
+ key_states = key_states.view(
754
+ bsz, q_len, self.num_key_value_heads, self.head_dim
755
+ ).transpose(1, 2)
756
+ value_states = value_states.view(
757
+ bsz, q_len, self.num_key_value_heads, self.head_dim
758
+ ).transpose(1, 2)
759
+
760
+ kv_seq_len = key_states.shape[-2]
761
+ if past_key_value is not None:
762
+ if self.layer_idx is None:
763
+ raise ValueError(
764
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
765
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
766
+ "with a layer index."
767
+ )
768
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
769
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
770
+ query_states, key_states = apply_rotary_pos_emb(
771
+ query_states, key_states, cos, sin, position_ids
772
+ )
773
+
774
+ if past_key_value is not None:
775
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
776
+ key_states, value_states = past_key_value.update(
777
+ key_states, value_states, self.layer_idx, cache_kwargs
778
+ )
779
+
780
+ # repeat k/v heads if n_kv_heads < n_heads
781
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
782
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
783
+
784
+ attn_weights = torch.matmul(
785
+ query_states, key_states.transpose(2, 3)
786
+ ) / math.sqrt(self.head_dim)
787
+
788
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
789
+ raise ValueError(
790
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
791
+ f" {attn_weights.size()}"
792
+ )
793
+
794
+ if attention_mask is not None:
795
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
796
+ raise ValueError(
797
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
798
+ )
799
+
800
+ attn_weights = attn_weights + attention_mask
801
+
802
+ # upcast attention to fp32
803
+ attn_weights = nn.functional.softmax(
804
+ attn_weights, dim=-1, dtype=torch.float32
805
+ ).to(query_states.dtype)
806
+ attn_weights = nn.functional.dropout(
807
+ attn_weights, p=self.attention_dropout, training=self.training
808
+ )
809
+ attn_output = torch.matmul(attn_weights, value_states)
810
+
811
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
812
+ raise ValueError(
813
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
814
+ f" {attn_output.size()}"
815
+ )
816
+
817
+ attn_output = attn_output.transpose(1, 2).contiguous()
818
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
819
+
820
+ attn_output = self.o_proj(attn_output)
821
+
822
+ if not output_attentions:
823
+ attn_weights = None
824
+
825
+ return attn_output, attn_weights, past_key_value
826
+
827
+
828
+ class MistralSparseSiluMLP(MistralMLP):
829
+ def __init__(self, config, *args, **kwargs):
830
+ super().__init__(config)
831
+ self.swish_outputs = None
832
+ self.relu = nn.ReLU()
833
+ self.resilu = nn.Sequential(nn.SiLU())
834
+
835
+ self.kill_sparse_swish_outputs = False
836
+ self.cut_pre_mlp = False
837
+ self.dead_percentage = 0
838
+ self.pre_mlp_sparsity = 0
839
+ self.is_stats = False
840
+ self.visit_counts = 0
841
+
842
+ # Hyperparameters to tune
843
+ self.dead_threshold = kwargs.pop("dead_threshold", 0)
844
+ self.pre_mlp_threshold = kwargs.pop("pre_mlp_threshold", 0)
845
+ self.pre_mlp_dead_threshold = kwargs.pop("pre_mlp_dead_threshold", 0)
846
+ self.use_sparse_regularization = kwargs.pop("use_sparse_regularization", True)
847
+ self.regularization_type = kwargs.pop(
848
+ "regularization_type", "L1 regularization"
849
+ )
850
+ self.regularization_threshold = kwargs.pop("regularization_threshold", 0.5)
851
+ self.use_relu = kwargs.pop("use_relu", False)
852
+ self.use_resilu = kwargs.pop("use_resilu", False)
853
+ self.activation_norm = None
854
+
855
+ # Activation Histograms
856
+ self.is_collect_histogram = False
857
+ num_bins = 1000
858
+ self.histogram_bins = torch.linspace(-1, 1, num_bins - 2)
859
+ self.histogram_bins = torch.cat(
860
+ [torch.tensor([-torch.inf]), self.histogram_bins, torch.tensor([torch.inf])]
861
+ )
862
+ self.pre_mlp_std = 0
863
+ # self.pre_mlp_hist_counts = torch.zeros(num_bins - 1)
864
+ self.pre_act_hist_counts = torch.zeros(num_bins - 1)
865
+ self.post_act_hist_counts = torch.zeros(num_bins - 1)
866
+ self.t = 0
867
+ self.count = 0
868
+ self.agg_sparsity = 0
869
+
870
+ # Sparse activation function
871
+ self.sparse_act_fn = SparseSiLU(threshold=self.dead_threshold)
872
+
873
+ def activate_stats(self, is_collect_histogram: bool = True):
874
+ self.is_stats = True
875
+ self.dead_percentage = 0
876
+ self.visit_counts = 0
877
+ self.is_collect_histogram = is_collect_histogram
878
+ self.histogram_counts = torch.zeros(2000) # .to(self.down_proj.weight.device)
879
+
880
+ def deactivate_stats(self):
881
+ self.is_stats = False
882
+
883
+ def collect_stats(
884
+ self,
885
+ pre_mlp,
886
+ pre_activation,
887
+ post_activation,
888
+ ):
889
+ start_time = time.time()
890
+ pre_activation = pre_activation.float().cpu().detach()
891
+ post_activation = post_activation.float().cpu().detach()
892
+ # self.histogram_bins=self.histogram_bins.to(pre_activation.device).type(pre_activation.dtype)
893
+ # self.pre_mlp_hist_counts = torch.histogram(pre_mlp, bins=self.histogram_bins)[0]
894
+ self.pre_act_hist_counts += torch.histogram(
895
+ pre_activation, bins=self.histogram_bins
896
+ )[0]
897
+ self.post_act_hist_counts += torch.histogram(
898
+ torch.abs(post_activation), bins=self.histogram_bins
899
+ )[0]
900
+ self.t += time.time() - start_time
901
+ if self.visit_counts % 30 == 0:
902
+ print(f"Time taken to collect stats: {self.t}s.")
903
+
904
+ def forward(
905
+ self,
906
+ x,
907
+ sp_mask: torch.tensor = None,
908
+ ):
909
+ """
910
+ If kill_sparse_swish_outputs is set to False, this layer functions exactly like a normal MLP layer.
911
+ """
912
+ if sp_mask != None: # When sparse mask is given
913
+ return self.down_proj(
914
+ self.sparse_act_fn(self.gate_proj(x) * sp_mask) * self.up_proj(x)
915
+ ) # Todo: This doesn't accelerate runtime (instead slowing down)
916
+
917
+ elif self.use_relu or self.use_resilu:
918
+ if self.use_relu:
919
+ post_act = self.relu(self.gate_proj(x))
920
+ else:
921
+ post_act = self.resilu(self.gate_proj(x))
922
+ self.count += 1
923
+ if self.count <= 1:
924
+ print("USING RELU or ReSiLU!!!!")
925
+
926
+ if self.is_stats:
927
+ dead_neurons = post_act == 0
928
+ dead_percentage = dead_neurons.float().mean()
929
+ agg_sparsity = dead_neurons.all(dim=0).float().mean()
930
+
931
+ self.dead_percentage = (
932
+ self.dead_percentage * self.visit_counts + dead_percentage
933
+ ) / (self.visit_counts + 1)
934
+ self.agg_sparsity = (
935
+ self.agg_sparsity * self.visit_counts + agg_sparsity
936
+ ) / (self.visit_counts + 1)
937
+ self.visit_counts += 1
938
+
939
+ return self.down_proj(post_act * self.up_proj(x))
940
+
941
+ else:
942
+ self.count += 1
943
+
944
+ if self.cut_pre_mlp:
945
+ if (
946
+ self.is_stats
947
+ ): # collect statistics for deciding threhold value to cut values of hidden vec before mlp
948
+ self.pre_mlp_std = (
949
+ x.std() * self.visit_counts + 0.6 * self.pre_mlp_std
950
+ ) / (self.visit_counts + 1)
951
+ self.count -= 1
952
+ x[abs(x) < self.pre_mlp_threshold] = 0
953
+
954
+ pre_act = self.gate_proj(x)
955
+ post_act = self.act_fn(pre_act)
956
+ if self.kill_sparse_swish_outputs:
957
+ dead_neurons = post_act.abs() <= self.dead_threshold
958
+ # print("pre act sparsity: ", (pre_act==0).float().mean())
959
+
960
+ dead_percentage = dead_neurons.float().mean()
961
+ agg_sparsity = dead_neurons.all(dim=0).float().mean()
962
+
963
+ if self.is_stats:
964
+ self.dead_percentage = (
965
+ self.dead_percentage * self.visit_counts + dead_percentage
966
+ ) / (self.visit_counts + 1)
967
+ self.agg_sparsity = (
968
+ self.agg_sparsity * self.visit_counts + agg_sparsity
969
+ ) / (self.visit_counts + 1)
970
+ self.pre_mlp_sparsity = (
971
+ self.pre_mlp_sparsity * self.visit_counts
972
+ + (x == 0).float().mean()
973
+ ) / (self.visit_counts + 1)
974
+
975
+ self.visit_counts += 1
976
+
977
+ self.a = dead_percentage
978
+
979
+ # print(self.agg_sparsity)
980
+
981
+ # Collect histogram stats
982
+ if (
983
+ self.is_collect_histogram
984
+ and pre_act.eq(0).float().mean() < 0.99
985
+ ): # Padded dataset
986
+ self.collect_stats(x, pre_act, post_act)
987
+
988
+ post_act[dead_neurons] = 0
989
+ if self.count == 10:
990
+ print(
991
+ f"sparsity: {dead_percentage}/ pre-activation sparsity: {(x==0).float().mean()}"
992
+ )
993
+
994
+ out = self.down_proj(post_act * self.up_proj(x))
995
+ if self.use_sparse_regularization:
996
+ if self.regularization_type == "L1 regularization":
997
+ self.activation_norm = torch.abs(post_act)[
998
+ post_act < self.regularization_threshold
999
+ ].mean()
1000
+ elif self.regularization_type == "L2 regularization":
1001
+ self.activation_norm = torch.sqrt(
1002
+ torch.square(post_act)[post_act < self.regularization_threshold]
1003
+ ).mean()
1004
+
1005
+ return out
1006
+
1007
+
1008
+ class SparseMistralDecoderLayer(MistralDecoderLayer):
1009
+ def __init__(
1010
+ self,
1011
+ config: MistralConfig,
1012
+ layer_idx: int,
1013
+ decoder_layer: MistralDecoderLayer,
1014
+ init_svd: bool = True,
1015
+ *args,
1016
+ **kwargs,
1017
+ ):
1018
+ assert isinstance(
1019
+ decoder_layer.mlp, MistralSparseSiluMLP
1020
+ ), f"{type(decoder_layer.mlp)} should MistralSparseSiluMLP."
1021
+
1022
+ super().__init__(config, layer_idx)
1023
+ self.hidden_size = config.hidden_size
1024
+ self.intermediate_size = config.intermediate_size
1025
+
1026
+ self.init_svd = init_svd
1027
+ self.self_attn = decoder_layer.self_attn
1028
+
1029
+ self.mlp = decoder_layer.mlp
1030
+ self.input_layernorm = decoder_layer.input_layernorm
1031
+ self.post_attention_layernorm = decoder_layer.post_attention_layernorm
1032
+
1033
+ # Sparse predictor for mlp (initialized with SVD decomposed matrix)
1034
+ self.low_rank = kwargs.pop("low_rank", 64)
1035
+ self.sparse_act_func = decoder_layer.mlp.sparse_act_fn
1036
+
1037
+ print(
1038
+ f"Setting {layer_idx}th mlp layer's sparse predictor... svd init: {init_svd}"
1039
+ )
1040
+ self.sp_mlp = low_rank_approximation(
1041
+ decoder_layer.mlp.gate_proj,
1042
+ act_func=self.sparse_act_func,
1043
+ init_svd=init_svd,
1044
+ )
1045
+ self.use_async = kwargs.pop("use_async", False)
1046
+ self.use_sparse_predictor = False
1047
+ self.distill_loss = None
1048
+
1049
+ def forward(
1050
+ self,
1051
+ hidden_states: torch.Tensor,
1052
+ attention_mask: Optional[torch.Tensor] = None,
1053
+ position_ids: Optional[torch.LongTensor] = None,
1054
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1055
+ output_attentions: Optional[bool] = False,
1056
+ use_cache: Optional[bool] = False,
1057
+ **kwargs,
1058
+ ) -> Tuple[
1059
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
1060
+ ]:
1061
+ print("hidden_states shape: ", hidden_states.shape)
1062
+ if "padding_mask" in kwargs:
1063
+ warnings.warn(
1064
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1065
+ )
1066
+
1067
+ residual = hidden_states
1068
+ sp_mask = None
1069
+
1070
+ if self.use_async:
1071
+ sp_mask = self.sp_mlp(hidden_states)
1072
+
1073
+ hidden_states = self.input_layernorm(hidden_states)
1074
+
1075
+ # Self Attention
1076
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1077
+ hidden_states=hidden_states,
1078
+ attention_mask=attention_mask,
1079
+ position_ids=position_ids,
1080
+ past_key_value=past_key_value,
1081
+ output_attentions=output_attentions,
1082
+ use_cache=use_cache,
1083
+ )
1084
+ hidden_states = residual + hidden_states
1085
+
1086
+ # Fully Connected
1087
+ residual = hidden_states
1088
+ hidden_states = self.post_attention_layernorm(hidden_states)
1089
+
1090
+ if not self.use_async:
1091
+ sp_mask = self.sp_mlp(hidden_states)
1092
+
1093
+ # Compute distillation loss
1094
+ gating_output = self.mlp.sparse_act_fn(self.mlp.gate_proj(hidden_states))
1095
+ loss_func = MSELoss()
1096
+ self.distill_loss = loss_func(sp_mask, gating_output)
1097
+
1098
+ # Convert sp mask into binary form
1099
+ sp_mask = sp_mask > 0
1100
+
1101
+ if self.training:
1102
+ sp_mask = None
1103
+ # if not self.use_sparse_predictor:
1104
+ # sp_mask = None
1105
+
1106
+ hidden_states = self.mlp(hidden_states, sp_mask)
1107
+ hidden_states = residual + hidden_states
1108
+
1109
+ outputs = (hidden_states,)
1110
+
1111
+ if output_attentions:
1112
+ outputs += (self_attn_weights,)
1113
+
1114
+ if use_cache:
1115
+ outputs += (present_key_value,)
1116
+
1117
+ return outputs
1118
+
1119
+
1120
+ class SparseMistralConfig(MistralConfig):
1121
+ model_type = "sparse_mistral"
1122
+
1123
+ def __init__(self, **kwargs):
1124
+ super().__init__(**kwargs)
1125
+
1126
+
1127
+ class SparseMistralforCausalLM(MistralForCausalLM):
1128
+ config_class = SparseMistralConfig
1129
+
1130
+ def __init__(self, config):
1131
+ super().__init__(config)
1132
+ self.config = config
1133
+ if config.use_sparse_model:
1134
+ self.apply_sparse_mlp()
1135
+ if config.thresholds is not None:
1136
+ for idx, m in enumerate(self.model.layers):
1137
+ if isinstance(m.mlp, MistralSparseSiluMLP):
1138
+ m.mlp.dead_threshold = config.thresholds[idx]
1139
+ m.mlp.pre_mlp_threshold = config.pre_mlp_thresholds[idx]
1140
+ m.mlp.sparse_act_fn.set_new_threshold(m.mlp.dead_threshold)
1141
+ m.mlp.kill_sparse_swish_outputs = True
1142
+ m.mlp.use_relu = getattr(config, "use_relu", False)
1143
+ m.mlp.use_resilu = getattr(config, "use_resilu", False)
1144
+ if isinstance(
1145
+ m.self_attn,
1146
+ (SparseMistralAttention, SparseMistralFlashAttention),
1147
+ ):
1148
+ m.self_attn.pre_mlp_threshold = config.pre_attn_thresholds[idx]
1149
+ if config.use_sparse_predictor:
1150
+ self.apply_sparse_predictor(init_svd=config.init_svd)
1151
+
1152
+ def apply_sparse_mlp(self):
1153
+ apply_mistral_sparse_silu_mlp(
1154
+ self,
1155
+ config=self.config,
1156
+ use_sparse_regularization=self.config.use_sparse_regularization,
1157
+ cut_pre_mlp=self.config.cut_pre_mlp,
1158
+ cut_pre_attn=self.config.cut_pre_attn,
1159
+ )
1160
+
1161
+ def apply_sparse_predictor(self, init_svd: bool = True):
1162
+ apply_mistral_sparse_decoder_layer(self, config=self.config, init_svd=init_svd)
1163
+
1164
+
1165
+ class GracefulRegularizationScheduler(TrainerCallback):
1166
+ def __init__(
1167
+ self,
1168
+ num_warmup_steps=40,
1169
+ is_enabled: bool = False,
1170
+ model_name: str = "mistral",
1171
+ test_dataset: Dataset = None,
1172
+ targeted_sparsity: float = 0.5,
1173
+ keep_regularization_with_kill: bool = False,
1174
+ ):
1175
+ """Scheduler for regularizing the model first before applying the dead threshold.
1176
+
1177
+ :param num_warmup_steps: number of training steps required to reach the dead threshold, defaults to 40
1178
+ :param increment_ratio: by how much to increase the dead threshold.
1179
+ For example, 0.5 means "increase the threshold by 0.5 * desired threshold
1180
+ """
1181
+ self.num_warmup_steps = num_warmup_steps
1182
+ self.is_enabled = is_enabled
1183
+ self.model_name = model_name
1184
+ self.test_dataset = test_dataset
1185
+ self.targeted_sparsity = targeted_sparsity
1186
+ self.keep_regularization_with_kill = keep_regularization_with_kill
1187
+ self.act_hist_path = (
1188
+ f"/matx/u/vxbrando/histograms/warm_up_reg_{targeted_sparsity}/act_hist.pt"
1189
+ )
1190
+ if self.is_enabled:
1191
+ print("GracefulRegularizationScheduler is enabled.")
1192
+ self.trainer = None
1193
+
1194
+ def set_trainer(self, trainer):
1195
+ self.trainer = trainer
1196
+
1197
+ def on_step_end(self, args, state, control, **kwargs):
1198
+ if not self.is_enabled:
1199
+ return
1200
+
1201
+ model = kwargs["model"]
1202
+ if isinstance(model, PeftModel):
1203
+ base_model = model.get_base_model()
1204
+ else:
1205
+ base_model = model
1206
+
1207
+ if state.global_step == 1:
1208
+ ds_print("Setting an initial reg threshold to 0.1")
1209
+ set_regularization_threshold(base_model, 0.1)
1210
+
1211
+ # if state.global_step >= self.num_warmup_steps and state.global_step % 50 == 0:
1212
+ if state.global_step == self.num_warmup_steps:
1213
+ activate_stats(base_model)
1214
+ enable_sparse_silu(base_model)
1215
+ self.trainer.evaluate()
1216
+ save_act_hist(base_model, self.act_hist_path)
1217
+ set_sparse_threshold(base_model, self.targeted_sparsity, True)
1218
+ deactivate_stats(base_model)
1219
+ self.trainer.use_sparse_regularization = self.keep_regularization_with_kill
1220
+ # set_layer_specific_regularization(model.get_base_model())
1221
+ print_dead_neuron_stats(model.get_base_model())
1222
+
1223
+ if state.global_step % 2000 == 0:
1224
+ if is_mainprocess():
1225
+ ds_print(
1226
+ f"Saving to /scr/lukeai/{self.model_name}_{state.global_step}.pt",
1227
+ )
1228
+ torch.save(
1229
+ model.state_dict(),
1230
+ f"/scr/lukeai/{self.model_name}_{state.global_step}.pt",
1231
+ )
1232
+
1233
+
1234
+ class GradualSparsificationScheduler(TrainerCallback):
1235
+ def __init__(
1236
+ self,
1237
+ num_warmup_steps=40,
1238
+ increment_ratio=0.5,
1239
+ is_enabled: bool = False,
1240
+ model_name: str = "mistral",
1241
+ ):
1242
+ """Scheduler for gradually increasing a dead threshold until it reaches the desired threshold.
1243
+
1244
+ :param num_warmup_steps: number of training steps required to reach the dead threshold, defaults to 40
1245
+ :param increment_ratio: by how much to increase the dead threshold.
1246
+ For example, 0.5 means "increase the threshold by 0.5 * desired threshold
1247
+ """
1248
+ self.num_warmup_steps = num_warmup_steps
1249
+ self.increment_ratio = increment_ratio
1250
+ self.step_size = int(num_warmup_steps * increment_ratio)
1251
+ self.is_enabled = is_enabled
1252
+ self.model_name = model_name
1253
+
1254
+ def on_step_end(self, args, state, control, **kwargs):
1255
+ model = kwargs["model"]
1256
+
1257
+ if not self.is_enabled:
1258
+ if state.global_step <= 10:
1259
+ for module in model.modules():
1260
+ if isinstance(module, MistralSparseSiluMLP):
1261
+ module.current_dead_threshold = module.dead_threshold
1262
+ return
1263
+
1264
+ current_dead_threshold = 0
1265
+ desired_dead_threshold = 0
1266
+
1267
+ if is_mainprocess():
1268
+ ds_print(state.global_step)
1269
+
1270
+ if state.global_step % self.step_size == 2:
1271
+ for module in model.modules():
1272
+ if isinstance(module, MistralSparseSiluMLP):
1273
+ desired_dead_threshold = copy.deepcopy(module.dead_threshold)
1274
+ current_dead_threshold = module.current_dead_threshold
1275
+ current_dead_threshold += (
1276
+ self.increment_ratio * desired_dead_threshold
1277
+ )
1278
+ module.current_dead_threshold = min(
1279
+ desired_dead_threshold, current_dead_threshold
1280
+ )
1281
+
1282
+ if is_running_deepspeed and is_mainprocess():
1283
+ ds_print(
1284
+ state.global_step,
1285
+ current_dead_threshold,
1286
+ desired_dead_threshold,
1287
+ )
1288
+
1289
+ if state.global_step % 2000 == 0:
1290
+ if is_running_deepspeed and is_mainprocess():
1291
+ ds_print(
1292
+ f"Saving to /matx/u/lukeai/{self.model_name}_{state.global_step - 2}.pt",
1293
+ )
1294
+ torch.save(
1295
+ model.state_dict(),
1296
+ f"/matx/u/lukeai/{self.model_name}_{state.global_step - 2}.pt",
1297
+ )
1298
+
1299
+
1300
+ def get_sparse_mistral_config(
1301
+ config: MistralConfig,
1302
+ use_sparse_model=False,
1303
+ use_sparse_predictor=False,
1304
+ use_sparse_regularization=False,
1305
+ thresholds=None,
1306
+ cut_pre_mlp=False,
1307
+ cut_pre_attn=False,
1308
+ ):
1309
+ new_config = SparseMistralConfig()
1310
+ new_config.__dict__.update(config.__dict__)
1311
+ config = new_config
1312
+ config.use_sparse_model = use_sparse_model
1313
+ config.use_sparse_predictor = use_sparse_predictor
1314
+ config.use_sparse_regularization = use_sparse_regularization
1315
+ config.thresholds = thresholds
1316
+ config.cut_pre_mlp = cut_pre_mlp
1317
+ config.cut_pre_attn = cut_pre_attn
1318
+
1319
+ return config
1320
+
1321
+
1322
+ def apply_mistral_sparse_silu_mlp(
1323
+ model,
1324
+ config,
1325
+ use_sparse_regularization: bool = False,
1326
+ use_flash_attn: bool = False,
1327
+ cut_pre_mlp: bool = False,
1328
+ cut_pre_attn: bool = False,
1329
+ ):
1330
+ for layer in model.model.layers:
1331
+ # counts += 1
1332
+ # if counts < 4:
1333
+ # continue
1334
+ original_mlp = layer.mlp
1335
+ new_mlp = MistralSparseSiluMLP(
1336
+ config, use_sparse_regularization=use_sparse_regularization
1337
+ )
1338
+ new_mlp.gate_proj = original_mlp.gate_proj
1339
+ new_mlp.up_proj = original_mlp.up_proj
1340
+ new_mlp.down_proj = original_mlp.down_proj
1341
+ new_mlp.cut_pre_mlp = cut_pre_mlp
1342
+ layer.mlp = new_mlp
1343
+ if cut_pre_attn:
1344
+ for layer in model.model.layers:
1345
+ original_attention = layer.self_attn
1346
+ if use_flash_attn:
1347
+ new_attention = SparseMistralFlashAttention(
1348
+ config=original_attention.config,
1349
+ layer_idx=original_attention.layer_idx,
1350
+ )
1351
+
1352
+ else:
1353
+ new_attention = SparseMistralAttention(
1354
+ config=original_attention.config,
1355
+ layer_idx=original_attention.layer_idx,
1356
+ )
1357
+ for attr in vars(original_attention):
1358
+ setattr(new_attention, attr, getattr(original_attention, attr))
1359
+ layer.self_attn = new_attention
1360
+
1361
+
1362
+ def apply_mistral_sparse_attention(
1363
+ model,
1364
+ config,
1365
+ ):
1366
+ for layer in model.model.layers:
1367
+ layer.self_attention = layer.self_attention
1368
+
1369
+
1370
+ def apply_mistral_sparse_decoder_layer(
1371
+ model,
1372
+ config,
1373
+ init_svd: bool = True,
1374
+ ):
1375
+ assert isinstance(model.model, MistralModel), "model.model must be a MistralModel."
1376
+ new_layers = []
1377
+ for layer_idx, layer in enumerate(model.model.layers):
1378
+ if isinstance(layer.mlp, MistralSparseSiluMLP):
1379
+ new_layers.append(
1380
+ SparseMistralDecoderLayer(
1381
+ config=config,
1382
+ layer_idx=layer_idx,
1383
+ decoder_layer=layer,
1384
+ init_svd=init_svd,
1385
+ )
1386
+ )
1387
+ print(f"{layer_idx}th mlp layer activation: {layer.mlp.sparse_act_fn}")
1388
+ else:
1389
+ new_layers.append(layer)
1390
+ model.model.layers = nn.ModuleList(new_layers)
1391
+
1392
+
1393
+ def enable_sparse_predictor(
1394
+ model,
1395
+ ):
1396
+ for layer_idx, layer in enumerate(model.model.layers):
1397
+ if isinstance(layer, MistralDecoderLayer):
1398
+ layer.use_sparse_predictor = True
1399
+
1400
+
1401
+ def disable_sparse_predictor(
1402
+ model,
1403
+ ):
1404
+ for layer_idx, layer in enumerate(model.model.layers):
1405
+ if isinstance(layer, MistralDecoderLayer):
1406
+ layer.use_sparse_predictor = False
1407
+
1408
+
1409
+ def activate_stats(model, is_collect_histogram: bool = True):
1410
+ for layer in model.model.layers:
1411
+ if isinstance(layer.mlp, MistralSparseSiluMLP):
1412
+ layer.mlp.activate_stats(is_collect_histogram=is_collect_histogram)
1413
+ if isinstance(layer.self_attn, SparseMistralAttention):
1414
+ layer.self_attn.activate_stats()
1415
+
1416
+
1417
+ def deactivate_stats(model):
1418
+ for layer in model.model.layers:
1419
+ if isinstance(layer.mlp, MistralSparseSiluMLP):
1420
+ layer.mlp.deactivate_stats()
1421
+
1422
+
1423
+ def enable_sparse_silu(model):
1424
+ print("Enabling SparseSilu")
1425
+ for i, layer in enumerate(model.model.layers):
1426
+ if isinstance(layer.mlp, MistralSparseSiluMLP):
1427
+ layer.mlp.kill_sparse_swish_outputs = True
1428
+
1429
+
1430
+ def print_dead_neuron_stats(model):
1431
+ total_sparsity = 0
1432
+ counts = 0
1433
+ for i, layer in enumerate(model.model.layers):
1434
+ if isinstance(layer.mlp, MistralSparseSiluMLP):
1435
+ dead_percentage = layer.mlp.dead_percentage * 100
1436
+ agg_sparsity = layer.mlp.agg_sparsity * 100
1437
+ pre_mlp_sparsity = layer.mlp.pre_mlp_sparsity * 100
1438
+ print(f"layer {i} sparsity: {dead_percentage:.3f}%")
1439
+ print(f"layer {i} agg sparsity: {agg_sparsity:.3f}%")
1440
+ print(f"layer {i} pre_mlp_sparsity: {pre_mlp_sparsity:.3f}%")
1441
+
1442
+ total_sparsity += dead_percentage
1443
+ counts += 1
1444
+ if isinstance(layer.self_attn, SparseMistralAttention) or isinstance(
1445
+ layer.self_attn, SparseMistralFlashAttention
1446
+ ):
1447
+ print(
1448
+ f"Attention layer {i} sparsity: {layer.self_attn.pre_attn_sparsity * 100: .3f}%"
1449
+ )
1450
+
1451
+ print(f"Total sparsity: {total_sparsity/counts: .3f}%")
1452
+ return total_sparsity / counts
1453
+
1454
+
1455
+ def get_sparse_layers(model: MistralModel):
1456
+ sparse_layers = [
1457
+ m.mlp for m in model.layers() if isinstance(m.mlp, MistralSparseSiluMLP)
1458
+ ]
1459
+ return sparse_layers
1460
+
1461
+
1462
+ def get_threshold(
1463
+ bin_edges: torch.tensor, histogram_counts: torch.tensor, sparsity_level: float
1464
+ ): # Only for L1 Regularization
1465
+ assert (
1466
+ len(bin_edges.shape) == len(histogram_counts.shape) == 1
1467
+ ), "bin_edges and histogram are expected to be 1-dimensional."
1468
+ histogram_counts /= histogram_counts.sum()
1469
+ threshold_idx = torch.searchsorted(
1470
+ histogram_counts.cumsum(0), sparsity_level, side="right"
1471
+ )
1472
+
1473
+ return bin_edges[threshold_idx]
1474
+
1475
+
1476
+ def set_regularization_threshold(model, threshold: float = 0.1):
1477
+ for i, layer in enumerate(model.model.layers):
1478
+ if (
1479
+ isinstance(layer.mlp, MistralSparseSiluMLP) and layer.mlp.is_stats
1480
+ ): # Can set the threshold only the relevant statistics is collected.
1481
+ layer.mlp.regularization_threshold = threshold # TODO: find better param
1482
+
1483
+
1484
+ def set_sparse_threshold(
1485
+ model, sparsity_level: float, use_relu: bool = False, use_resilu: bool = False
1486
+ ):
1487
+ assert not (use_relu and use_resilu), "It's not allowed to use both relu and resilu"
1488
+ for i, layer in enumerate(model.model.layers):
1489
+ if (
1490
+ isinstance(layer.mlp, MistralSparseSiluMLP) and layer.mlp.is_stats
1491
+ ): # Can set the threshold only the relevant statistics is collected.
1492
+ if use_relu:
1493
+ layer.mlp.sparse_act_fn = nn.ReLU()
1494
+ layer.mlp.use_relu = True
1495
+ layer.mlp.use_resilu = False
1496
+ elif use_resilu:
1497
+ layer.mlp.sparse_act_fn = nn.Sequential(nn.ReLU(), nn.SiLU())
1498
+ layer.mlp.use_resilu = True
1499
+ layer.mlp.use_relu = False
1500
+ else:
1501
+ layer.mlp.dead_threshold = get_threshold(
1502
+ layer.mlp.histogram_bins,
1503
+ layer.mlp.post_act_hist_counts,
1504
+ sparsity_level,
1505
+ )
1506
+ layer.mlp.sparse_act_fn.set_new_threshold(layer.mlp.dead_threshold)
1507
+ layer.mlp.regularization_threshold = (
1508
+ layer.mlp.dead_threshold * 1.2
1509
+ ) # TODO: find better param
1510
+
1511
+ if layer.mlp.cut_pre_mlp:
1512
+ layer.mlp.pre_mlp_threshold = layer.mlp.pre_mlp_std
1513
+ print(f"layer {i} pre-mlp threshold: {layer.mlp.pre_mlp_threshold}")
1514
+
1515
+ if isinstance(
1516
+ layer.self_attn, (SparseMistralAttention, SparseMistralFlashAttention)
1517
+ ):
1518
+ layer.self_attn.pre_attn_threshold = layer.self_attn.pre_attn_std
1519
+ print(f"layer {i} pre-attn threshold: {layer.self_attn.pre_attn_threshold}")
1520
+
1521
+
1522
+ def plot_histogram(
1523
+ bin_edges,
1524
+ histogram_counts: torch.tensor,
1525
+ title: str = "Activation Distribution",
1526
+ fig_dir: str = "figures",
1527
+ ):
1528
+ plt.bar(
1529
+ bin_edges[:-1], histogram_counts, width=np.diff(bin_edges), edgecolor="black"
1530
+ )
1531
+ plt.title(title)
1532
+ plt.xlabel("Activation Value")
1533
+ plt.ylabel("Frequency")
1534
+ os.makedirs(fig_dir, exist_ok=True)
1535
+ plt.savefig(f"{fig_dir}/{title}.png")
1536
+ # plt.show()
1537
+ plt.clf()
1538
+
1539
+
1540
+ def plot_act(model, fig_dir: str = "figures"):
1541
+ for i, layer in enumerate(model.model.layers):
1542
+ if (
1543
+ isinstance(layer.mlp, MistralSparseSiluMLP) and layer.mlp.is_stats
1544
+ ): # Can set the threshold only the relevant statistics is collected.
1545
+ plot_title = f"Layer: {i} Pre-Activation Distribution"
1546
+ plot_histogram(
1547
+ layer.mlp.histogram_bins, layer.mlp.pre_act_hist_counts, plot_title
1548
+ )
1549
+
1550
+ plot_title = f"Layer: {i} Post-Activation Absolute Distribution"
1551
+ plot_histogram(
1552
+ layer.mlp.histogram_bins, layer.mlp.post_act_hist_counts, plot_title
1553
+ )
1554
+
1555
+
1556
+ def save_act_hist(
1557
+ model, filename="/scr/jay/models/mistral/pre_finetune/cola_act_hist.pt"
1558
+ ):
1559
+ os.makedirs(os.path.dirname(filename), exist_ok=True)
1560
+ act_dict = {}
1561
+ for i, layer in enumerate(model.model.layers):
1562
+ if (
1563
+ isinstance(layer.mlp, MistralSparseSiluMLP) and layer.mlp.is_stats
1564
+ ): # Can set the threshold only the relevant statistics is collected.
1565
+ act_dict[i] = (
1566
+ layer.mlp.histogram_bins,
1567
+ # layer.mlp.pre_mlp_hist_counts,
1568
+ layer.mlp.pre_act_hist_counts,
1569
+ layer.mlp.post_act_hist_counts,
1570
+ )
1571
+ print("Saving activation histograms...\n\n\n")
1572
+ torch.save(act_dict, filename)
1573
+
1574
+
1575
+ def load_act_hist(
1576
+ model, filename="/scr/jay/models/mistral/pre_finetune/cola_act_hist.pt"
1577
+ ):
1578
+ assert os.path.exists(
1579
+ filename
1580
+ ), f"{filename} does not exist when loading pre/post-activation histogram of SparseMistralSiluMLP."
1581
+ print("Loading activation histograms...\n\n\n")
1582
+
1583
+ act_dict = torch.load(filename)
1584
+ for i, layer in enumerate(model.model.layers):
1585
+ if (
1586
+ isinstance(layer.mlp, MistralSparseSiluMLP) and layer.mlp.is_stats
1587
+ ): # Can set the threshold only the relevant statistics is collected.
1588
+ (
1589
+ layer.mlp.histogram_bins,
1590
+ # layer.mlp.pre_mlp_hist_counts,
1591
+ layer.mlp.pre_act_hist_counts,
1592
+ layer.mlp.post_act_hist_counts,
1593
+ ) = act_dict[i]
1594
+
1595
+
1596
+ def enable_last_k_modules(model, start_module_idx: int):
1597
+ assert 32 > start_module_idx >= 0
1598
+ new_modules = []
1599
+ new_idx = 0
1600
+ for idx in range(start_module_idx, len(model.model.original_layers)):
1601
+ module = model.model.original_layers[idx]
1602
+ module.layer_idx = new_idx
1603
+ module.self_attn.layer_idx = new_idx
1604
+ new_modules.append(module)
1605
+ new_idx += 1
1606
+ print(module.layer_idx)
1607
+
1608
+ model.model.layers = nn.ModuleList(new_modules)
1609
+
1610
+
1611
+ def enable_first_k_modules(model, end_module_idx: int):
1612
+ assert 32 > end_module_idx >= 0
1613
+ new_modules = []
1614
+ new_idx = 0
1615
+ for idx in range(0, end_module_idx + 1):
1616
+ module = model.model.original_layers[idx]
1617
+ module.layer_idx = new_idx
1618
+ module.self_attn.layer_idx = new_idx
1619
+ new_modules.append(module)
1620
+ new_idx += 1
1621
+ print(module.layer_idx)
1622
+
1623
+ model.model.layers = nn.ModuleList(new_modules)