vxbrandon commited on
Commit
f7c6674
·
verified ·
1 Parent(s): ca7cef8

End of training

Browse files
README.md ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_resilu_2024-03-13
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_resilu_2024-03-13
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.6723
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: 350
49
+
50
+ ### Training results
51
+
52
+ | Training Loss | Epoch | Step | Validation Loss |
53
+ |:-------------:|:-----:|:----:|:---------------:|
54
+ | 8.8267 | 0.0 | 25 | 8.7790 |
55
+ | 8.3017 | 0.01 | 50 | 8.3269 |
56
+ | 7.8921 | 0.01 | 75 | 7.9440 |
57
+ | 7.6064 | 0.02 | 100 | 7.6915 |
58
+ | 7.4736 | 0.02 | 125 | 7.5597 |
59
+ | 7.0663 | 0.02 | 150 | 6.8821 |
60
+ | 4.695 | 0.03 | 175 | 4.5616 |
61
+ | 3.6054 | 0.03 | 200 | 3.7193 |
62
+ | 3.2379 | 0.04 | 225 | 3.3697 |
63
+ | 3.0502 | 0.04 | 250 | 3.1769 |
64
+ | 2.8841 | 0.04 | 275 | 3.0628 |
65
+ | 2.8355 | 0.05 | 300 | 2.9948 |
66
+ | 2.7938 | 0.05 | 325 | 2.9511 |
67
+ | 2.5994 | 0.06 | 350 | 2.9099 |
68
+
69
+
70
+ ### Framework versions
71
+
72
+ - Transformers 4.36.2
73
+ - Pytorch 2.1.2+cu121
74
+ - Datasets 2.15.0
75
+ - Tokenizers 0.15.0
config.json ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "mistralai/Mistral-7B-v0.1",
3
+ "architectures": [
4
+ "SparseMistralforCausalLM"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "sparsification_sftt.SparseMistralConfig",
9
+ "AutoModelForCausalLM": "sparsification_sftt.SparseMistralforCausalLM"
10
+ },
11
+ "bos_token_id": 1,
12
+ "eos_token_id": 2,
13
+ "hidden_act": "silu",
14
+ "hidden_size": 4096,
15
+ "initializer_range": 0.02,
16
+ "intermediate_size": 14336,
17
+ "max_position_embeddings": 32768,
18
+ "model_type": "sparse_mistral",
19
+ "num_attention_heads": 32,
20
+ "num_hidden_layers": 32,
21
+ "num_key_value_heads": 8,
22
+ "rms_norm_eps": 1e-05,
23
+ "rope_theta": 10000.0,
24
+ "sliding_window": 4096,
25
+ "thresholds": [
26
+ 0.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
+ 0.0
58
+ ],
59
+ "tie_word_embeddings": false,
60
+ "torch_dtype": "bfloat16",
61
+ "transformers_version": "4.36.2",
62
+ "use_cache": false,
63
+ "use_relu": false,
64
+ "use_resilu": true,
65
+ "use_sparse_model": true,
66
+ "use_sparse_predictor": false,
67
+ "use_sparse_regularization": false,
68
+ "vocab_size": 32000
69
+ }
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "transformers_version": "4.36.2"
6
+ }
model-00001-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:86d637a4d398c23032fef196657a8fb2999e7131c2bb177c53467a3beeb2d396
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:0a23b7f46fad7b387bc5a57941af4e6aecd9c940ae513135c9ab15f88ad68cda
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:7f872861640b013c9f3ad47a8316e383699964bc4aa5056f94832a670d97a89b
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,988 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
9
+ import warnings
10
+ import torch
11
+ import torch.nn as nn
12
+ import torch.nn.functional as F
13
+ import matplotlib.pyplot as plt
14
+ import numpy as np
15
+ import time
16
+ import os
17
+ import copy
18
+
19
+ from transformers.models.mistral.modeling_mistral import (
20
+ MistralMLP,
21
+ MistralAttention,
22
+ MistralModel,
23
+ MistralDecoderLayer,
24
+ MistralConfig,
25
+ MISTRAL_ATTENTION_CLASSES,
26
+ MistralRMSNorm,
27
+ MistralForCausalLM,
28
+ )
29
+ from experiments.models.sparse_mistral.svd_router import (
30
+ low_rank_approximation,
31
+ SparsePredictor,
32
+ )
33
+ from utils.utils import (
34
+ print_size_of_model,
35
+ is_running_deepspeed,
36
+ is_mainprocess,
37
+ get_datetime,
38
+ ds_print,
39
+ )
40
+
41
+
42
+ class SparseSFTTTrainer(SFTTrainer):
43
+ def __init__(self, *args, **kwargs):
44
+ self.regularization_coefficient = kwargs.pop("regularization_coefficient", 10)
45
+ self.use_sparse_regularization = kwargs.pop("use_sparse_regularization", False)
46
+ self.use_spm_loss = False
47
+ self.freeze_original_weights = False
48
+ self.regularization_type = kwargs.pop(
49
+ "regularization_type", "L1 positive activation"
50
+ )
51
+ assert self.regularization_type in [
52
+ "L2 activation",
53
+ "L1 positive activation",
54
+ ], f"Invalid regularization type: {self.regularization_type}"
55
+ self.sparse_layers = []
56
+ self.sparse_decoder_layers = []
57
+ super(SparseSFTTTrainer, self).__init__(*args, **kwargs)
58
+
59
+ def initialize_sparse_silu_layers(self, model):
60
+ self.sparse_layers = [
61
+ m for m in model.modules() if isinstance(m, MistralSparseSiluMLP)
62
+ ]
63
+
64
+ def initialize_sparse_decoder_layers(self, model):
65
+ self.sparse_decoder_layers = [
66
+ m for m in model.modules() if isinstance(m, SparseMistralDecoderLayer)
67
+ ]
68
+
69
+ def training_step(
70
+ self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]]
71
+ ) -> torch.Tensor:
72
+ """
73
+ Override the huggingface's training_step function to add a regularization term.
74
+ A regularization term is computed with intermediate values, which are freed after "backward()."
75
+ You need to set `retain_graph=True` inside `backward` function to keep the values.
76
+ """
77
+ model.train()
78
+ inputs = self._prepare_inputs(inputs)
79
+
80
+ with self.compute_loss_context_manager():
81
+ loss = self.compute_loss(model, inputs)
82
+
83
+ if self.args.n_gpu > 1:
84
+ loss = loss.mean() # mean() to average on multi-gpu parallel training
85
+ if not self.freeze_original_weights:
86
+ if loss is not None:
87
+ self.accelerator.backward(loss, retain_graph=False)
88
+
89
+ if self.use_sparse_regularization:
90
+ regularization_loss = self.compute_regularization(model)
91
+ if self.args.n_gpu > 1:
92
+ regularization_loss = regularization_loss.mean()
93
+ if regularization_loss is not None:
94
+ self.accelerator.backward(regularization_loss, retain_graph=True)
95
+ loss += regularization_loss
96
+
97
+ if self.use_spm_loss:
98
+ spm_loss = self.compute_spm_loss(model)
99
+ if self.args.n_gpu > 1:
100
+ spm_loss = spm_loss.mean()
101
+ if spm_loss is not None:
102
+ self.accelerator.backward(spm_loss, retain_graph=False)
103
+ loss += spm_loss
104
+
105
+ return loss.detach() / self.args.gradient_accumulation_steps
106
+
107
+ def compute_regularization(self, model):
108
+ """
109
+ Compute a sparse regularization loss for SiLU
110
+ """
111
+ loss = 0
112
+ if len(self.sparse_layers) == 0:
113
+ self.initialize_sparse_silu_layers(model)
114
+ num_layers = len(self.sparse_layers)
115
+
116
+ for module in self.sparse_layers:
117
+ if module.activation_norm is not None:
118
+ loss += module.activation_norm
119
+
120
+ loss /= num_layers
121
+ loss *= self.regularization_coefficient
122
+
123
+ if self.state.global_step % 20 == 0 and loss != 0:
124
+ print("Negative relularizer loss: ", loss.item())
125
+ return loss
126
+
127
+ def compute_spm_loss(self, model):
128
+ loss = 0
129
+ if len(self.sparse_decoder_layers) == 0:
130
+ self.initialize_sparse_decoder_layers(model)
131
+ for module in self.sparse_decoder_layers:
132
+ if module.distill_loss != None:
133
+ loss += module.distill_loss
134
+ if self.state.global_step % 20 == 0 and loss != 0:
135
+ print("Sparse Predictor Distillation loss: ", loss.item())
136
+ return loss
137
+
138
+ # def compute_loss(self, model, inputs, return_outputs=False):
139
+ # loss = super().compute_loss(model, inputs, return_outputs)
140
+ #
141
+ # if is_sagemaker_mp_enabled():
142
+ # import smdistributed.modelparallel.torch as smp
143
+ # @smp.step()
144
+ # def smp_forward_backward(model, inputs, gradient_accumulation_steps=1):
145
+ # outputs = model(**inputs)
146
+ # loss = outputs["loss"] if isinstance(outputs, dict) else outputs[0]
147
+ # loss /= gradient_accumulation_steps
148
+ # model.backward(loss)
149
+ # return loss
150
+ #
151
+ # loss_mb = smp_forward_backward(
152
+ # model, inputs, self.args.gradient_accumulation_steps
153
+ # )
154
+ # if self.use_sparse_regularization:
155
+ # return loss_mb.reduce_mean().detach().to(
156
+ # self.args.device
157
+ # ) + self.regularization_coefficient * self.compute_regularization(model)
158
+ # else:
159
+ # return loss_mb.reduce_mean().detach().to(self)
160
+ #
161
+ # if return_outputs:
162
+ # classification_loss, outputs = loss
163
+ # else:
164
+ # classification_loss = loss
165
+ #
166
+ # loss = classification_loss
167
+ # if self.use_sparse_regularization:
168
+ # regularization_loss = self.compute_regularization(model)
169
+ # loss += self.regularization_coefficient * regularization_loss
170
+ #
171
+ # return (loss, outputs) if return_outputs else loss
172
+
173
+
174
+ class SparseTrainer(Trainer):
175
+ def __init__(self, *args, **kwargs):
176
+ self.regularization_coefficient = kwargs.pop("regularization_coefficient", 10)
177
+ self.use_sparse_regularization = kwargs.pop("use_sparse_regularization", False)
178
+ self.use_spm_loss = False
179
+ self.freeze_original_weights = False
180
+ self.regularization_type = kwargs.pop(
181
+ "regularization_type", "L1 positive activation"
182
+ )
183
+ assert self.regularization_type in [
184
+ "L2 activation",
185
+ "L1 positive activation",
186
+ ], f"Invalid regularization type: {self.regularization_type}"
187
+ self.sparse_layers = []
188
+ self.sparse_decoder_layers = []
189
+ super(SparseTrainer, self).__init__(*args, **kwargs)
190
+
191
+ def initialize_sparse_silu_layers(self, model):
192
+ self.sparse_layers = [
193
+ m for m in model.modules() if isinstance(m, MistralSparseSiluMLP)
194
+ ]
195
+
196
+ def initialize_sparse_decoder_layers(self, model):
197
+ self.sparse_decoder_layers = [
198
+ m for m in model.modules() if isinstance(m, SparseMistralDecoderLayer)
199
+ ]
200
+
201
+ def training_step(
202
+ self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]]
203
+ ) -> torch.Tensor:
204
+ """
205
+ Override the huggingface's training_step function to add a regularization term.
206
+ A regularization term is computed with intermediate values, which are freed after "backward()."
207
+ You need to set `retain_graph=True` inside `backward` function to keep the values.
208
+ """
209
+ model.train()
210
+ inputs = self._prepare_inputs(inputs)
211
+
212
+ with self.compute_loss_context_manager():
213
+ loss = self.compute_loss(model, inputs)
214
+
215
+ if self.args.n_gpu > 1:
216
+ loss = loss.mean() # mean() to average on multi-gpu parallel training
217
+ if not self.freeze_original_weights:
218
+ if loss is not None:
219
+ self.accelerator.backward(loss, retain_graph=False)
220
+
221
+ if self.use_sparse_regularization:
222
+ regularization_loss = self.compute_regularization(model)
223
+ if self.args.n_gpu > 1:
224
+ regularization_loss = regularization_loss.mean()
225
+ if regularization_loss is not None:
226
+ self.accelerator.backward(regularization_loss, retain_graph=True)
227
+ loss += regularization_loss
228
+
229
+ if self.use_spm_loss:
230
+ spm_loss = self.compute_spm_loss(model)
231
+ if self.args.n_gpu > 1:
232
+ spm_loss = spm_loss.mean()
233
+ if spm_loss is not None:
234
+ self.accelerator.backward(spm_loss, retain_graph=False)
235
+ loss += spm_loss
236
+
237
+ return loss.detach() / self.args.gradient_accumulation_steps
238
+
239
+ def compute_regularization(self, model):
240
+ """
241
+ Compute a sparse regularization loss for SiLU
242
+ """
243
+ loss = 0
244
+ if len(self.sparse_layers) == 0:
245
+ self.initialize_sparse_silu_layers(model)
246
+ num_layers = len(self.sparse_layers)
247
+
248
+ for module in self.sparse_layers:
249
+ if module.activation_norm is not None:
250
+ loss += module.activation_norm
251
+
252
+ loss /= num_layers
253
+ loss *= self.regularization_coefficient
254
+
255
+ if self.state.global_step % 20 == 0 and loss != 0:
256
+ print("Negative relularizer loss: ", loss.item())
257
+ return loss
258
+
259
+ def compute_spm_loss(self, model):
260
+ loss = 0
261
+ if len(self.sparse_decoder_layers) == 0:
262
+ self.initialize_sparse_decoder_layers(model)
263
+ for module in self.sparse_decoder_layers:
264
+ if module.distill_loss != None:
265
+ loss += module.distill_loss
266
+ if self.state.global_step % 20 == 0 and loss != 0:
267
+ print("Sparse Predictor Distillation loss: ", loss.item())
268
+ return loss
269
+
270
+
271
+ class SparseSiLU(nn.SiLU):
272
+ def __init__(self, threshold):
273
+ super(SparseSiLU, self).__init__()
274
+ self.threshold = threshold
275
+ self.m = nn.Threshold(self.threshold, 0)
276
+
277
+ def set_new_threshold(self, threshold):
278
+ self.threshold = threshold
279
+ self.m = nn.Threshold(threshold, 0)
280
+
281
+ def forward(self, x):
282
+ act = super(SparseSiLU, self).forward(x)
283
+ return self.m(act) - self.m(-act)
284
+
285
+
286
+ class MistralSparseSiluMLP(MistralMLP):
287
+ def __init__(self, config, *args, **kwargs):
288
+ super().__init__(config)
289
+ self.swish_outputs = None
290
+ self.relu = nn.ReLU()
291
+ self.resilu = nn.Sequential(nn.ReLU(), nn.SiLU())
292
+
293
+ self.kill_sparse_swish_outputs = False
294
+ self.dead_percentage = 0
295
+ self.is_stats = False
296
+ self.visit_counts = 0
297
+
298
+ # Hyperparameters to tune
299
+ self.dead_threshold = kwargs.pop("dead_threshold", 0)
300
+ self.use_sparse_regularization = kwargs.pop("use_sparse_regularization", True)
301
+ self.regularization_type = kwargs.pop(
302
+ "regularization_type", "L1 regularization"
303
+ )
304
+ self.regularization_threshold = kwargs.pop("regularization_threshold", 0.5)
305
+ self.use_relu = kwargs.pop("use_relu", False)
306
+ self.use_resilu = kwargs.pop("use_resilu", False)
307
+ self.activation_norm = None
308
+
309
+ # Activation Histograms
310
+ self.is_collect_histogram = False
311
+ num_bins = 1000
312
+ self.histogram_bins = torch.linspace(-1, 1, num_bins - 2)
313
+ self.histogram_bins = torch.cat(
314
+ [torch.tensor([-torch.inf]), self.histogram_bins, torch.tensor([torch.inf])]
315
+ )
316
+ self.pre_act_hist_counts = torch.zeros(num_bins - 1)
317
+ self.post_act_hist_counts = torch.zeros(num_bins - 1)
318
+ self.t = 0
319
+ self.count = 0
320
+ self.agg_sparsity = 0
321
+
322
+ # Sparse activation function
323
+ self.sparse_act_fn = SparseSiLU(threshold=self.dead_threshold)
324
+
325
+ def activate_stats(self, is_collect_histogram: bool = True):
326
+ self.is_stats = True
327
+ self.dead_percentage = 0
328
+ self.visit_counts = 0
329
+ self.is_collect_histogram = is_collect_histogram
330
+ self.histogram_counts = torch.zeros(2000) # .to(self.down_proj.weight.device)
331
+
332
+ def deactivate_stats(self):
333
+ self.is_stats = False
334
+
335
+ def collect_stats(self, pre_activation, post_activation):
336
+ start_time = time.time()
337
+ pre_activation = pre_activation.float().cpu().detach()
338
+ post_activation = post_activation.float().cpu().detach()
339
+ # self.histogram_bins=self.histogram_bins.to(pre_activation.device).type(pre_activation.dtype)
340
+ self.pre_act_hist_counts += torch.histogram(
341
+ pre_activation, bins=self.histogram_bins
342
+ )[0]
343
+ self.post_act_hist_counts += torch.histogram(
344
+ torch.abs(post_activation), bins=self.histogram_bins
345
+ )[0]
346
+ self.t += time.time() - start_time
347
+ if self.visit_counts % 30 == 0:
348
+ print(f"Time taken to collect stats: {self.t}s.")
349
+
350
+ def forward(
351
+ self,
352
+ x,
353
+ sp_mask: torch.tensor = None,
354
+ ):
355
+ """
356
+ If kill_sparse_swish_outputs is set to False, this layer functions exactly like a normal MLP layer.
357
+ """
358
+ if sp_mask != None: # When sparse mask is given
359
+ return self.down_proj(
360
+ self.sparse_act_fn(self.gate_proj(x) * sp_mask) * self.up_proj(x)
361
+ ) # Todo: This doesn't accelerate runtime (instead slowing down)
362
+
363
+ elif self.use_relu or self.use_resilu:
364
+ if self.use_relu:
365
+ post_act = self.relu(self.gate_proj(x))
366
+ else:
367
+ post_act = self.resilu(self.gate_proj(x))
368
+ self.count += 1
369
+ if self.count <= 1:
370
+ print("USING RELU or ReSiLU!!!!")
371
+
372
+ if self.is_stats:
373
+ dead_neurons = post_act == 0
374
+ dead_percentage = dead_neurons.float().mean()
375
+ agg_sparsity = dead_neurons.all(dim=0).float().mean()
376
+
377
+ self.dead_percentage = (
378
+ self.dead_percentage * self.visit_counts + dead_percentage
379
+ ) / (self.visit_counts + 1)
380
+ self.agg_sparsity = (
381
+ self.agg_sparsity * self.visit_counts + agg_sparsity
382
+ ) / (self.visit_counts + 1)
383
+ self.visit_counts += 1
384
+
385
+ return self.down_proj(post_act * self.up_proj(x))
386
+
387
+ else:
388
+ self.count += 1
389
+ if self.count <= 1:
390
+ print("USING SparseSILU!!!!")
391
+ pre_act = self.gate_proj(x)
392
+ post_act = self.act_fn(pre_act)
393
+ if self.kill_sparse_swish_outputs:
394
+ dead_neurons = post_act.abs() <= self.dead_threshold
395
+ # print("pre act sparsity: ", (pre_act==0).float().mean())
396
+
397
+ dead_percentage = dead_neurons.float().mean()
398
+ agg_sparsity = dead_neurons.all(dim=0).float().mean()
399
+
400
+ if self.is_stats:
401
+ self.dead_percentage = (
402
+ self.dead_percentage * self.visit_counts + dead_percentage
403
+ ) / (self.visit_counts + 1)
404
+ self.agg_sparsity = (
405
+ self.agg_sparsity * self.visit_counts + agg_sparsity
406
+ ) / (self.visit_counts + 1)
407
+ self.visit_counts += 1
408
+
409
+ self.a = dead_percentage
410
+
411
+ # print(self.agg_sparsity)
412
+
413
+ # Collect histogram stats
414
+ if (
415
+ self.is_collect_histogram
416
+ and pre_act.eq(0).float().mean() < 0.99
417
+ ): # Padded dataset
418
+ self.collect_stats(pre_act, post_act)
419
+
420
+ post_act[dead_neurons] = 0
421
+
422
+ out = self.down_proj(post_act * self.up_proj(x))
423
+ if self.use_sparse_regularization:
424
+ if self.regularization_type == "L1 regularization":
425
+ self.activation_norm = torch.abs(post_act)[
426
+ post_act < self.regularization_threshold
427
+ ].mean()
428
+ elif self.regularization_type == "L2 regularization":
429
+ self.activation_norm = torch.sqrt(
430
+ torch.square(post_act)[post_act < self.regularization_threshold]
431
+ ).mean()
432
+
433
+ return out
434
+
435
+
436
+ class SparseMistralDecoderLayer(MistralDecoderLayer):
437
+ def __init__(
438
+ self,
439
+ config: MistralConfig,
440
+ layer_idx: int,
441
+ decoder_layer: MistralDecoderLayer,
442
+ init_svd: bool = True,
443
+ *args,
444
+ **kwargs,
445
+ ):
446
+ assert isinstance(
447
+ decoder_layer.mlp, MistralSparseSiluMLP
448
+ ), f"{type(decoder_layer.mlp)} should MistralSparseSiluMLP."
449
+
450
+ super().__init__(config, layer_idx)
451
+ self.hidden_size = config.hidden_size
452
+ self.intermediate_size = config.intermediate_size
453
+
454
+ self.init_svd = init_svd
455
+ self.self_attn = decoder_layer.self_attn
456
+
457
+ self.mlp = decoder_layer.mlp
458
+ self.input_layernorm = decoder_layer.input_layernorm
459
+ self.post_attention_layernorm = decoder_layer.post_attention_layernorm
460
+
461
+ # Sparse predictor for mlp (initialized with SVD decomposed matrix)
462
+ self.low_rank = kwargs.pop("low_rank", 64)
463
+ self.sparse_act_func = decoder_layer.mlp.sparse_act_fn
464
+
465
+ print(
466
+ f"Setting {layer_idx}th mlp layer's sparse predictor... svd init: {init_svd}"
467
+ )
468
+ self.sp_mlp = low_rank_approximation(
469
+ decoder_layer.mlp.gate_proj,
470
+ act_func=self.sparse_act_func,
471
+ init_svd=init_svd,
472
+ )
473
+ self.use_async = kwargs.pop("use_async", False)
474
+ self.use_sparse_predictor = False
475
+ self.distill_loss = None
476
+
477
+ def forward(
478
+ self,
479
+ hidden_states: torch.Tensor,
480
+ attention_mask: Optional[torch.Tensor] = None,
481
+ position_ids: Optional[torch.LongTensor] = None,
482
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
483
+ output_attentions: Optional[bool] = False,
484
+ use_cache: Optional[bool] = False,
485
+ **kwargs,
486
+ ) -> Tuple[
487
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
488
+ ]:
489
+ print("hidden_states shape: ", hidden_states.shape)
490
+ if "padding_mask" in kwargs:
491
+ warnings.warn(
492
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
493
+ )
494
+
495
+ residual = hidden_states
496
+ sp_mask = None
497
+
498
+ if self.use_async:
499
+ sp_mask = self.sp_mlp(hidden_states)
500
+
501
+ hidden_states = self.input_layernorm(hidden_states)
502
+
503
+ # Self Attention
504
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
505
+ hidden_states=hidden_states,
506
+ attention_mask=attention_mask,
507
+ position_ids=position_ids,
508
+ past_key_value=past_key_value,
509
+ output_attentions=output_attentions,
510
+ use_cache=use_cache,
511
+ )
512
+ hidden_states = residual + hidden_states
513
+
514
+ # Fully Connected
515
+ residual = hidden_states
516
+ hidden_states = self.post_attention_layernorm(hidden_states)
517
+
518
+ if not self.use_async:
519
+ sp_mask = self.sp_mlp(hidden_states)
520
+
521
+ # Compute distillation loss
522
+ gating_output = self.mlp.sparse_act_fn(self.mlp.gate_proj(hidden_states))
523
+ loss_func = MSELoss()
524
+ self.distill_loss = loss_func(sp_mask, gating_output)
525
+
526
+ # Convert sp mask into binary form
527
+ sp_mask = sp_mask > 0
528
+
529
+ if self.training:
530
+ sp_mask = None
531
+ # if not self.use_sparse_predictor:
532
+ # sp_mask = None
533
+
534
+ hidden_states = self.mlp(hidden_states, sp_mask)
535
+ hidden_states = residual + hidden_states
536
+
537
+ outputs = (hidden_states,)
538
+
539
+ if output_attentions:
540
+ outputs += (self_attn_weights,)
541
+
542
+ if use_cache:
543
+ outputs += (present_key_value,)
544
+
545
+ return outputs
546
+
547
+
548
+ class SparseMistralConfig(MistralConfig):
549
+ model_type = "sparse_mistral"
550
+
551
+ def __init__(self, **kwargs):
552
+ super().__init__(**kwargs)
553
+
554
+
555
+ class SparseMistralforCausalLM(MistralForCausalLM):
556
+ config_class = SparseMistralConfig
557
+
558
+ def __init__(self, config):
559
+ super().__init__(config)
560
+ self.config = config
561
+ if config.use_sparse_model:
562
+ self.apply_sparse_mlp()
563
+ if config.thresholds is not None:
564
+ for idx, m in enumerate(self.model.layers):
565
+ if isinstance(m.mlp, MistralSparseSiluMLP):
566
+ m.mlp.dead_threshold = config.thresholds[idx]
567
+ m.mlp.sparse_act_fn.set_new_threshold(m.mlp.dead_threshold)
568
+ m.mlp.kill_sparse_swish_outputs = True
569
+ m.mlp.use_relu = getattr(config, "use_relu", False)
570
+ m.mlp.use_resilu = getattr(config, "use_resilu", False)
571
+ if config.use_sparse_predictor:
572
+ self.apply_sparse_predictor(init_svd=config.init_svd)
573
+
574
+ def apply_sparse_mlp(self):
575
+ apply_mistral_sparse_silu_mlp(
576
+ self,
577
+ config=self.config,
578
+ use_sparse_regularization=self.config.use_sparse_regularization,
579
+ )
580
+
581
+ def apply_sparse_predictor(self, init_svd: bool = True):
582
+ apply_mistral_sparse_decoder_layer(self, config=self.config, init_svd=init_svd)
583
+
584
+
585
+ class GracefulRegularizationScheduler(TrainerCallback):
586
+ def __init__(
587
+ self,
588
+ num_warmup_steps=40,
589
+ is_enabled: bool = False,
590
+ model_name: str = "mistral",
591
+ test_dataset: Dataset = None,
592
+ targeted_sparsity: float = 0.5,
593
+ keep_regularization_with_kill: bool = False,
594
+ ):
595
+ """Scheduler for regularizing the model first before applying the dead threshold.
596
+
597
+ :param num_warmup_steps: number of training steps required to reach the dead threshold, defaults to 40
598
+ :param increment_ratio: by how much to increase the dead threshold.
599
+ For example, 0.5 means "increase the threshold by 0.5 * desired threshold
600
+ """
601
+ self.num_warmup_steps = num_warmup_steps
602
+ self.is_enabled = is_enabled
603
+ self.model_name = model_name
604
+ self.test_dataset = test_dataset
605
+ self.targeted_sparsity = targeted_sparsity
606
+ self.keep_regularization_with_kill = keep_regularization_with_kill
607
+ self.act_hist_path = (
608
+ f"/matx/u/vxbrando/histograms/warm_up_reg_{targeted_sparsity}/act_hist.pt"
609
+ )
610
+ if self.is_enabled:
611
+ print("GracefulRegularizationScheduler is enabled.")
612
+ self.trainer = None
613
+
614
+ def set_trainer(self, trainer):
615
+ self.trainer = trainer
616
+
617
+ def on_step_end(self, args, state, control, **kwargs):
618
+ if not self.is_enabled:
619
+ return
620
+
621
+ model = kwargs["model"]
622
+ if isinstance(model, PeftModel):
623
+ base_model = model.get_base_model()
624
+ else:
625
+ base_model = model
626
+
627
+ if state.global_step == 1:
628
+ ds_print("Setting an initial reg threshold to 0.1")
629
+ set_regularization_threshold(base_model, 0.1)
630
+
631
+ # if state.global_step >= self.num_warmup_steps and state.global_step % 50 == 0:
632
+ if state.global_step == self.num_warmup_steps:
633
+ activate_stats(base_model)
634
+ enable_sparse_silu(base_model)
635
+ self.trainer.evaluate()
636
+ save_act_hist(base_model, self.act_hist_path)
637
+ set_sparse_threshold(base_model, self.targeted_sparsity, True)
638
+ deactivate_stats(base_model)
639
+ self.trainer.use_sparse_regularization = self.keep_regularization_with_kill
640
+ # set_layer_specific_regularization(model.get_base_model())
641
+ print_dead_neuron_stats(model.get_base_model())
642
+
643
+ if state.global_step % 2000 == 0:
644
+ if is_mainprocess():
645
+ ds_print(
646
+ f"Saving to /scr/lukeai/{self.model_name}_{state.global_step}.pt",
647
+ )
648
+ torch.save(
649
+ model.state_dict(),
650
+ f"/scr/lukeai/{self.model_name}_{state.global_step}.pt",
651
+ )
652
+
653
+
654
+ class GradualSparsificationScheduler(TrainerCallback):
655
+ def __init__(
656
+ self,
657
+ num_warmup_steps=40,
658
+ increment_ratio=0.5,
659
+ is_enabled: bool = False,
660
+ model_name: str = "mistral",
661
+ ):
662
+ """Scheduler for gradually increasing a dead threshold until it reaches the desired threshold.
663
+
664
+ :param num_warmup_steps: number of training steps required to reach the dead threshold, defaults to 40
665
+ :param increment_ratio: by how much to increase the dead threshold.
666
+ For example, 0.5 means "increase the threshold by 0.5 * desired threshold
667
+ """
668
+ self.num_warmup_steps = num_warmup_steps
669
+ self.increment_ratio = increment_ratio
670
+ self.step_size = int(num_warmup_steps * increment_ratio)
671
+ self.is_enabled = is_enabled
672
+ self.model_name = model_name
673
+
674
+ def on_step_end(self, args, state, control, **kwargs):
675
+ model = kwargs["model"]
676
+
677
+ if not self.is_enabled:
678
+ if state.global_step <= 10:
679
+ for module in model.modules():
680
+ if isinstance(module, MistralSparseSiluMLP):
681
+ module.current_dead_threshold = module.dead_threshold
682
+ return
683
+
684
+ current_dead_threshold = 0
685
+ desired_dead_threshold = 0
686
+
687
+ if is_mainprocess():
688
+ ds_print(state.global_step)
689
+
690
+ if state.global_step % self.step_size == 2:
691
+ for module in model.modules():
692
+ if isinstance(module, MistralSparseSiluMLP):
693
+ desired_dead_threshold = copy.deepcopy(module.dead_threshold)
694
+ current_dead_threshold = module.current_dead_threshold
695
+ current_dead_threshold += (
696
+ self.increment_ratio * desired_dead_threshold
697
+ )
698
+ module.current_dead_threshold = min(
699
+ desired_dead_threshold, current_dead_threshold
700
+ )
701
+
702
+ if is_running_deepspeed and is_mainprocess():
703
+ ds_print(
704
+ state.global_step,
705
+ current_dead_threshold,
706
+ desired_dead_threshold,
707
+ )
708
+
709
+ if state.global_step % 2000 == 0:
710
+ if is_running_deepspeed and is_mainprocess():
711
+ ds_print(
712
+ f"Saving to /matx/u/lukeai/{self.model_name}_{state.global_step - 2}.pt",
713
+ )
714
+ torch.save(
715
+ model.state_dict(),
716
+ f"/matx/u/lukeai/{self.model_name}_{state.global_step - 2}.pt",
717
+ )
718
+
719
+
720
+ def get_sparse_mistral_config(
721
+ config: MistralConfig,
722
+ use_sparse_model=False,
723
+ use_sparse_predictor=False,
724
+ use_sparse_regularization=False,
725
+ thresholds=None,
726
+ ):
727
+ new_config = SparseMistralConfig()
728
+ new_config.__dict__.update(config.__dict__)
729
+ config = new_config
730
+ config.use_sparse_model = use_sparse_model
731
+ config.use_sparse_predictor = use_sparse_predictor
732
+ config.use_sparse_regularization = use_sparse_regularization
733
+ config.thresholds = thresholds
734
+
735
+ return config
736
+
737
+
738
+ def apply_mistral_sparse_silu_mlp(
739
+ model,
740
+ config,
741
+ use_sparse_regularization: bool = False,
742
+ ):
743
+ # counts = 0
744
+ for layer in model.model.layers:
745
+ # counts += 1
746
+ # if counts < 4:
747
+ # continue
748
+ original_mlp = layer.mlp
749
+ new_mlp = MistralSparseSiluMLP(
750
+ config, use_sparse_regularization=use_sparse_regularization
751
+ )
752
+ new_mlp.gate_proj = original_mlp.gate_proj
753
+ new_mlp.up_proj = original_mlp.up_proj
754
+ new_mlp.down_proj = original_mlp.down_proj
755
+ layer.mlp = new_mlp
756
+
757
+
758
+ def apply_mistral_sparse_decoder_layer(
759
+ model,
760
+ config,
761
+ init_svd: bool = True,
762
+ ):
763
+ assert isinstance(model.model, MistralModel), "model.model must be a MistralModel."
764
+ new_layers = []
765
+ for layer_idx, layer in enumerate(model.model.layers):
766
+ if isinstance(layer.mlp, MistralSparseSiluMLP):
767
+ new_layers.append(
768
+ SparseMistralDecoderLayer(
769
+ config=config,
770
+ layer_idx=layer_idx,
771
+ decoder_layer=layer,
772
+ init_svd=init_svd,
773
+ )
774
+ )
775
+ print(f"{layer_idx}th mlp layer activation: {layer.mlp.sparse_act_fn}")
776
+ else:
777
+ new_layers.append(layer)
778
+ model.model.layers = nn.ModuleList(new_layers)
779
+
780
+
781
+ def enable_sparse_predictor(
782
+ model,
783
+ ):
784
+ for layer_idx, layer in enumerate(model.model.layers):
785
+ if isinstance(layer, MistralDecoderLayer):
786
+ layer.use_sparse_predictor = True
787
+
788
+
789
+ def disable_sparse_predictor(
790
+ model,
791
+ ):
792
+ for layer_idx, layer in enumerate(model.model.layers):
793
+ if isinstance(layer, MistralDecoderLayer):
794
+ layer.use_sparse_predictor = False
795
+
796
+
797
+ def activate_stats(model, is_collect_histogram: bool = True):
798
+ for layer in model.model.layers:
799
+ if isinstance(layer.mlp, MistralSparseSiluMLP):
800
+ layer.mlp.activate_stats(is_collect_histogram=is_collect_histogram)
801
+
802
+
803
+ def deactivate_stats(model):
804
+ for layer in model.model.layers:
805
+ if isinstance(layer.mlp, MistralSparseSiluMLP):
806
+ layer.mlp.deactivate_stats()
807
+
808
+
809
+ def enable_sparse_silu(model):
810
+ print("Enabling SparseSilu")
811
+ for i, layer in enumerate(model.model.layers):
812
+ if isinstance(layer.mlp, MistralSparseSiluMLP):
813
+ layer.mlp.kill_sparse_swish_outputs = True
814
+
815
+
816
+ def print_dead_neuron_stats(model):
817
+ total_sparsity = 0
818
+ counts = 0
819
+ for i, layer in enumerate(model.model.layers):
820
+ if isinstance(layer.mlp, MistralSparseSiluMLP):
821
+ dead_percentage = layer.mlp.dead_percentage * 100
822
+ agg_sparsity = layer.mlp.agg_sparsity * 100
823
+ print(f"layer {i} sparsity: {dead_percentage:.3f}%")
824
+ print(f"layer {i} agg sparsity: {agg_sparsity:.3f}%")
825
+ total_sparsity += dead_percentage
826
+ counts += 1
827
+
828
+ print(f"Total sparsity: {total_sparsity/counts: .3f}%")
829
+ return total_sparsity / counts
830
+
831
+
832
+ def get_sparse_layers(model: MistralModel):
833
+ sparse_layers = [
834
+ m.mlp for m in model.layers() if isinstance(m.mlp, MistralSparseSiluMLP)
835
+ ]
836
+ return sparse_layers
837
+
838
+
839
+ def get_threshold(
840
+ bin_edges: torch.tensor, histogram_counts: torch.tensor, sparsity_level: float
841
+ ): # Only for L1 Regularization
842
+ assert (
843
+ len(bin_edges.shape) == len(histogram_counts.shape) == 1
844
+ ), "bin_edges and histogram are expected to be 1-dimensional."
845
+ histogram_counts /= histogram_counts.sum()
846
+ threshold_idx = torch.searchsorted(
847
+ histogram_counts.cumsum(0), sparsity_level, side="right"
848
+ )
849
+
850
+ return bin_edges[threshold_idx]
851
+
852
+
853
+ def set_regularization_threshold(model, threshold: float = 0.1):
854
+ for i, layer in enumerate(model.model.layers):
855
+ if (
856
+ isinstance(layer.mlp, MistralSparseSiluMLP) and layer.mlp.is_stats
857
+ ): # Can set the threshold only the relevant statistics is collected.
858
+ layer.mlp.regularization_threshold = threshold # TODO: find better param
859
+
860
+
861
+ def set_sparse_threshold(
862
+ model, sparsity_level: float, use_relu: bool = False, use_resilu: bool = False
863
+ ):
864
+ assert not (use_relu and use_resilu), "It's not allowed to use both relu and resilu"
865
+ for i, layer in enumerate(model.model.layers):
866
+ if (
867
+ isinstance(layer.mlp, MistralSparseSiluMLP) and layer.mlp.is_stats
868
+ ): # Can set the threshold only the relevant statistics is collected.
869
+ if use_relu:
870
+ layer.mlp.sparse_act_fn = nn.ReLU()
871
+ layer.mlp.use_relu = True
872
+ layer.mlp.use_resilu = False
873
+ elif use_resilu:
874
+ layer.mlp.sparse_act_fn = nn.Sequential(nn.ReLU(), nn.SiLU())
875
+ layer.mlp.use_resilu = True
876
+ layer.mlp.use_relu = False
877
+ else:
878
+ layer.mlp.dead_threshold = get_threshold(
879
+ layer.mlp.histogram_bins,
880
+ layer.mlp.post_act_hist_counts,
881
+ sparsity_level,
882
+ )
883
+ layer.mlp.sparse_act_fn.set_new_threshold(layer.mlp.dead_threshold)
884
+ layer.mlp.regularization_threshold = (
885
+ layer.mlp.dead_threshold * 1.2
886
+ ) # TODO: find better param
887
+
888
+
889
+ def plot_histogram(
890
+ bin_edges,
891
+ histogram_counts: torch.tensor,
892
+ title: str = "Activation Distribution",
893
+ fig_dir: str = "figures",
894
+ ):
895
+ plt.bar(
896
+ bin_edges[:-1], histogram_counts, width=np.diff(bin_edges), edgecolor="black"
897
+ )
898
+ plt.title(title)
899
+ plt.xlabel("Activation Value")
900
+ plt.ylabel("Frequency")
901
+ os.makedirs(fig_dir, exist_ok=True)
902
+ plt.savefig(f"{fig_dir}/{title}.png")
903
+ # plt.show()
904
+ plt.clf()
905
+
906
+
907
+ def plot_act(model, fig_dir: str = "figures"):
908
+ for i, layer in enumerate(model.model.layers):
909
+ if (
910
+ isinstance(layer.mlp, MistralSparseSiluMLP) and layer.mlp.is_stats
911
+ ): # Can set the threshold only the relevant statistics is collected.
912
+ plot_title = f"Layer: {i} Pre-Activation Distribution"
913
+ plot_histogram(
914
+ layer.mlp.histogram_bins, layer.mlp.pre_act_hist_counts, plot_title
915
+ )
916
+
917
+ plot_title = f"Layer: {i} Post-Activation Absolute Distribution"
918
+ plot_histogram(
919
+ layer.mlp.histogram_bins, layer.mlp.post_act_hist_counts, plot_title
920
+ )
921
+
922
+
923
+ def save_act_hist(
924
+ model, filename="/scr/jay/models/mistral/pre_finetune/cola_act_hist.pt"
925
+ ):
926
+ os.makedirs(os.path.dirname(filename), exist_ok=True)
927
+ act_dict = {}
928
+ for i, layer in enumerate(model.model.layers):
929
+ if (
930
+ isinstance(layer.mlp, MistralSparseSiluMLP) and layer.mlp.is_stats
931
+ ): # Can set the threshold only the relevant statistics is collected.
932
+ act_dict[i] = (
933
+ layer.mlp.histogram_bins,
934
+ layer.mlp.pre_act_hist_counts,
935
+ layer.mlp.post_act_hist_counts,
936
+ )
937
+ print("Saving activation histograms...\n\n\n")
938
+ torch.save(act_dict, filename)
939
+
940
+
941
+ def load_act_hist(
942
+ model, filename="/scr/jay/models/mistral/pre_finetune/cola_act_hist.pt"
943
+ ):
944
+ assert os.path.exists(
945
+ filename
946
+ ), f"{filename} does not exist when loading pre/post-activation histogram of SparseMistralSiluMLP."
947
+ print("Loading activation histograms...\n\n\n")
948
+
949
+ act_dict = torch.load(filename)
950
+ for i, layer in enumerate(model.model.layers):
951
+ if (
952
+ isinstance(layer.mlp, MistralSparseSiluMLP) and layer.mlp.is_stats
953
+ ): # Can set the threshold only the relevant statistics is collected.
954
+ (
955
+ layer.mlp.histogram_bins,
956
+ layer.mlp.pre_act_hist_counts,
957
+ layer.mlp.post_act_hist_counts,
958
+ ) = act_dict[i]
959
+
960
+
961
+ def enable_last_k_modules(model, start_module_idx: int):
962
+ assert 32 > start_module_idx >= 0
963
+ new_modules = []
964
+ new_idx = 0
965
+ for idx in range(start_module_idx, len(model.model.original_layers)):
966
+ module = model.model.original_layers[idx]
967
+ module.layer_idx = new_idx
968
+ module.self_attn.layer_idx = new_idx
969
+ new_modules.append(module)
970
+ new_idx += 1
971
+ print(module.layer_idx)
972
+
973
+ model.model.layers = nn.ModuleList(new_modules)
974
+
975
+
976
+ def enable_first_k_modules(model, end_module_idx: int):
977
+ assert 32 > end_module_idx >= 0
978
+ new_modules = []
979
+ new_idx = 0
980
+ for idx in range(0, end_module_idx + 1):
981
+ module = model.model.original_layers[idx]
982
+ module.layer_idx = new_idx
983
+ module.self_attn.layer_idx = new_idx
984
+ new_modules.append(module)
985
+ new_idx += 1
986
+ print(module.layer_idx)
987
+
988
+ model.model.layers = nn.ModuleList(new_modules)