vxbrandon commited on
Commit
628157b
·
verified ·
1 Parent(s): 2dbe818

End of training

Browse files
README.md ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: llama2
3
+ base_model: meta-llama/Llama-2-7b-hf
4
+ tags:
5
+ - generated_from_trainer
6
+ model-index:
7
+ - name: sparse_llama_7b_hf2_refined_web_50p_2024-05-11
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
+ # sparse_llama_7b_hf2_refined_web_50p_2024-05-11
15
+
16
+ This model is a fine-tuned version of [meta-llama/Llama-2-7b-hf](https://huggingface.co/meta-llama/Llama-2-7b-hf) on the None dataset.
17
+ It achieves the following results on the evaluation set:
18
+ - Loss: 2.2840
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: 4
40
+ - seed: 0
41
+ - distributed_type: multi-GPU
42
+ - gradient_accumulation_steps: 8
43
+ - total_train_batch_size: 8
44
+ - optimizer: Adam with betas=(0.9,0.999) and epsilon=1e-08
45
+ - lr_scheduler_type: linear
46
+ - training_steps: 350
47
+
48
+ ### Training results
49
+
50
+ | Training Loss | Epoch | Step | Validation Loss |
51
+ |:-------------:|:-----:|:----:|:---------------:|
52
+ | 2.201 | 0.0 | 25 | 2.2172 |
53
+ | 2.2379 | 0.0 | 50 | 2.2154 |
54
+ | 2.1411 | 0.01 | 75 | 2.2137 |
55
+ | 2.1523 | 0.01 | 100 | 2.2125 |
56
+ | 2.5823 | 0.01 | 125 | 2.2103 |
57
+ | 2.2672 | 0.01 | 150 | 2.2063 |
58
+ | 2.3044 | 0.01 | 175 | 2.2036 |
59
+ | 2.2119 | 0.02 | 200 | 2.2012 |
60
+ | 2.1888 | 0.02 | 225 | 2.2004 |
61
+ | 2.1592 | 0.02 | 250 | 2.1981 |
62
+ | 2.2455 | 0.02 | 275 | 2.1972 |
63
+ | 2.0666 | 0.02 | 300 | 2.1972 |
64
+ | 2.322 | 0.03 | 325 | 2.1967 |
65
+ | 2.2689 | 0.03 | 350 | 2.1946 |
66
+
67
+
68
+ ### Framework versions
69
+
70
+ - Transformers 4.36.2
71
+ - Pytorch 2.1.2+cu121
72
+ - Datasets 2.19.1
73
+ - Tokenizers 0.15.2
config.json ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "meta-llama/Llama-2-7b-hf",
3
+ "architectures": [
4
+ "SparseLlamaForCausalLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "ugly_utils.SparseLlamaConfig",
10
+ "AutoModelForCausalLM": "ugly_utils.SparseLlamaForCausalLM"
11
+ },
12
+ "bos_token_id": 1,
13
+ "eos_token_id": 2,
14
+ "hidden_act": "silu",
15
+ "hidden_size": 4096,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 11008,
18
+ "max_position_embeddings": 4096,
19
+ "model_type": "sparse_llama",
20
+ "num_attention_heads": 32,
21
+ "num_hidden_layers": 32,
22
+ "num_key_value_heads": 32,
23
+ "pretraining_tp": 1,
24
+ "rms_norm_eps": 1e-05,
25
+ "rope_scaling": null,
26
+ "rope_theta": 10000.0,
27
+ "thresholds": [
28
+ 0.021063182502985,
29
+ 0.029087254777550697,
30
+ 0.03309928998351097,
31
+ 0.04513540118932724,
32
+ 0.061183542013168335,
33
+ 0.07723169028759003,
34
+ 0.08324974030256271,
35
+ 0.09127381443977356,
36
+ 0.08726178109645844,
37
+ 0.09127381443977356,
38
+ 0.09729187190532684,
39
+ 0.09528584778308868,
40
+ 0.0992978885769844,
41
+ 0.10531593859195709,
42
+ 0.10732196271419525,
43
+ 0.11334001272916794,
44
+ 0.11935807019472122,
45
+ 0.11735205352306366,
46
+ 0.12136408686637878,
47
+ 0.11133399605751038,
48
+ 0.10531593859195709,
49
+ 0.10130390524864197,
50
+ 0.10130390524864197,
51
+ 0.10330992192029953,
52
+ 0.10531593859195709,
53
+ 0.11133399605751038,
54
+ 0.1153460294008255,
55
+ 0.12337010353803635,
56
+ 0.13340020179748535,
57
+ 0.14744232594966888,
58
+ 0.1574724167585373,
59
+ 0.15947842597961426
60
+ ],
61
+ "tie_word_embeddings": false,
62
+ "torch_dtype": "bfloat16",
63
+ "transformers_version": "4.36.2",
64
+ "us_sparse_regularization": false,
65
+ "use_cache": false,
66
+ "use_graceful_regularization": false,
67
+ "use_relu": false,
68
+ "use_sparse_model": true,
69
+ "use_sparse_predictor": false,
70
+ "use_sparse_regularization": false,
71
+ "vocab_size": 32000
72
+ }
generation_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 1,
3
+ "do_sample": true,
4
+ "eos_token_id": 2,
5
+ "max_length": 4096,
6
+ "pad_token_id": 0,
7
+ "temperature": 0.6,
8
+ "top_p": 0.9,
9
+ "transformers_version": "4.36.2"
10
+ }
model-00001-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1a4fd2a79d8ffbe808d2c2ea4d0bd40d42d0124b1ee869536fe03b85f39d8009
3
+ size 4938985352
model-00002-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3ad5d08f9d9201c4efc073088ffaf7916d335b674dee7649ef51aa8d57046323
3
+ size 4947390880
model-00003-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:34edc553f00682dc58972738c70149fbaef17576b1f28e9fad845e55f2857b71
3
+ size 3590488816
model.safetensors.index.json ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 13476831232
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-00001-of-00003.safetensors",
27
+ "model.layers.10.mlp.down_proj.weight": "model-00001-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-00001-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-00001-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-00001-of-00003.safetensors",
41
+ "model.layers.11.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
42
+ "model.layers.11.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
43
+ "model.layers.11.self_attn.v_proj.weight": "model-00001-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-00002-of-00003.safetensors",
144
+ "model.layers.22.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
145
+ "model.layers.22.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
146
+ "model.layers.22.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
147
+ "model.layers.22.post_attention_layernorm.weight": "model-00002-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-00002-of-00003.safetensors",
155
+ "model.layers.23.mlp.up_proj.weight": "model-00002-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-00002-of-00003.safetensors",
158
+ "model.layers.23.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
159
+ "model.layers.23.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
160
+ "model.layers.23.self_attn.v_proj.weight": "model-00002-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
+ }
ugly_utils.py ADDED
@@ -0,0 +1,1356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Tuple
2
+ import torch
3
+ import torch.nn as nn
4
+ from torch.nn import MSELoss
5
+ import matplotlib.pyplot as plt
6
+ import numpy as np
7
+ import os
8
+ import time
9
+ import os
10
+ import copy
11
+ import warnings
12
+ from datasets import Dataset
13
+ from peft import PeftModel
14
+ from transformers import TrainerCallback
15
+ import matplotlib.pyplot as plt
16
+ import numpy as np
17
+ import time
18
+ import os
19
+ import copy
20
+ from transformers import Trainer
21
+ from typing import Any, Dict, Union
22
+ import torch
23
+ import torch.nn as nn
24
+ import torch.nn.functional as F
25
+ import flash_gemv
26
+ import seaborn as sns
27
+
28
+ # from experiments.models.sparse_silu.utils import get_mlp_class, get_decoder_class
29
+
30
+
31
+ from utils.utils import (
32
+ is_running_deepspeed,
33
+ is_mainprocess,
34
+ ds_print,
35
+ get_model_type,
36
+ get_model_type_from_name,
37
+ )
38
+ from utils.constants import MISTRAL
39
+ from transformers.configuration_utils import PretrainedConfig
40
+
41
+ # Mistral
42
+ from transformers.models.mistral.modeling_mistral import (
43
+ MistralMLP,
44
+ MistralDecoderLayer,
45
+ MistralConfig,
46
+ MistralForCausalLM,
47
+ MistralModel,
48
+ )
49
+ from experiments.models.sparse_mistral.svd_router import (
50
+ low_rank_approximation,
51
+ )
52
+
53
+ # Llama
54
+ from transformers.models.llama.modeling_llama import (
55
+ LlamaModel,
56
+ LlamaMLP,
57
+ LlamaDecoderLayer,
58
+ LlamaConfig,
59
+ LlamaForCausalLM,
60
+ )
61
+
62
+
63
+ def get_mlp_class(model):
64
+ model_type = get_model_type(model)
65
+ return MistralSparseSiluMLP if model_type == MISTRAL else LlamaSparseSiluMLP
66
+
67
+
68
+ def get_decoder_class(model):
69
+ model_type = get_model_type(model)
70
+ return (
71
+ SparseMistralDecoderLayer if model_type == MISTRAL else LlamaSparseDecoderLayer
72
+ )
73
+
74
+
75
+ def get_model_class(model):
76
+ model_type = get_model_type(model)
77
+ return MistralModel if model_type == MISTRAL else LlamaModel
78
+
79
+
80
+ class SparseSiLU(nn.SiLU):
81
+ def __init__(self, threshold):
82
+ super(SparseSiLU, self).__init__()
83
+ self.threshold = threshold
84
+ self.m = nn.Threshold(self.threshold, 0)
85
+
86
+ def set_new_threshold(self, threshold):
87
+ self.threshold = threshold
88
+ self.m = nn.Threshold(threshold, 0)
89
+
90
+ def forward(self, x):
91
+ act = super(SparseSiLU, self).forward(x)
92
+ return self.m(act) - self.m(-act)
93
+
94
+
95
+ def get_sparse_config(
96
+ config: PretrainedConfig,
97
+ model_type: str = None,
98
+ use_sparse_model=False,
99
+ use_sparse_predictor=False,
100
+ use_sparse_regularization=False,
101
+ use_graceful_regularization=False,
102
+ thresholds=None,
103
+ ):
104
+ if model_type == MISTRAL:
105
+ new_config = SparseMistralConfig()
106
+ else:
107
+ new_config = SparseLlamaConfig()
108
+ new_config.__dict__.update(config.__dict__)
109
+ config = new_config
110
+ config.use_sparse_model = use_sparse_model
111
+ config.use_sparse_predictor = use_sparse_predictor
112
+ config.use_sparse_regularization = use_sparse_regularization
113
+ config.use_graceful_regularization = use_graceful_regularization
114
+ config.thresholds = thresholds
115
+
116
+ return config
117
+
118
+
119
+ def apply_sparse_silu_mlp(
120
+ model,
121
+ config,
122
+ use_sparse_regularization: bool = False,
123
+ ):
124
+ SparseMLP = get_mlp_class(model)
125
+ for layer in model.model.layers:
126
+ original_mlp = layer.mlp
127
+ new_mlp = SparseMLP(config, use_sparse_regularization=use_sparse_regularization)
128
+ new_mlp.gate_proj = original_mlp.gate_proj
129
+ new_mlp.up_proj = original_mlp.up_proj
130
+ new_mlp.down_proj = original_mlp.down_proj
131
+ layer.mlp = new_mlp
132
+
133
+
134
+ def apply_sparse_decoder_layer(
135
+ model,
136
+ config,
137
+ init_svd: bool = True,
138
+ ):
139
+ Model = get_model_type(model)
140
+ SparseMLP = get_mlp_class(model)
141
+ DecoderLayer = get_decoder_class(model)
142
+
143
+ assert isinstance(model.model, Model), "model.model must be a MistralModel."
144
+ new_layers = []
145
+ for layer_idx, layer in enumerate(model.model.layers):
146
+ if isinstance(layer.mlp, SparseMLP):
147
+ new_layers.append(
148
+ DecoderLayer(
149
+ config=config,
150
+ layer_idx=layer_idx,
151
+ decoder_layer=layer,
152
+ init_svd=init_svd,
153
+ )
154
+ )
155
+ print(f"{layer_idx}th mlp layer activation: {layer.mlp.sparse_act_fn}")
156
+ else:
157
+ new_layers.append(layer)
158
+ model.model.layers = nn.ModuleList(new_layers)
159
+
160
+
161
+ def enable_sparse_predictor(
162
+ model,
163
+ ):
164
+ DecoderLayer = get_decoder_class(model)
165
+ for layer_idx, layer in enumerate(model.model.layers):
166
+ if isinstance(layer, DecoderLayer):
167
+ layer.use_sparse_predictor = True
168
+
169
+
170
+ def disable_sparse_predictor(
171
+ model,
172
+ ):
173
+ DecoderLayer = get_decoder_class(model)
174
+ for layer_idx, layer in enumerate(model.model.layers):
175
+ if isinstance(layer, DecoderLayer):
176
+ layer.use_sparse_predictor = False
177
+
178
+
179
+ def activate_stats(model, is_collect_histogram: bool = True):
180
+ SparseMLP = get_mlp_class(model)
181
+ for layer in model.model.layers:
182
+ if isinstance(layer.mlp, SparseMLP):
183
+ layer.mlp.activate_stats(is_collect_histogram=is_collect_histogram)
184
+
185
+
186
+ def deactivate_stats(
187
+ model,
188
+ ):
189
+ SparseMLP = get_mlp_class(model)
190
+ for layer in model.model.layers:
191
+ if isinstance(layer.mlp, SparseMLP):
192
+ layer.mlp.deactivate_stats()
193
+
194
+
195
+ def enable_sparse_silu(model):
196
+ print("Enabling SparseSilu")
197
+ SparseMLP = get_mlp_class(model)
198
+ for i, layer in enumerate(model.model.layers):
199
+ if isinstance(layer.mlp, SparseMLP):
200
+ layer.mlp.kill_sparse_swish_outputs = True
201
+
202
+
203
+ def disable_sparse_silu(model):
204
+ print("Disabling SparseSilu")
205
+ SparseMLP = get_mlp_class(model)
206
+ for i, layer in enumerate(model.model.layers):
207
+ if isinstance(layer.mlp, SparseMLP):
208
+ layer.mlp.kill_sparse_swish_outputs = False
209
+
210
+
211
+ def print_dead_neuron_stats(model):
212
+ SparseMLP = get_mlp_class(model)
213
+ total_sparsity = 0
214
+ counts = 0
215
+ for i, layer in enumerate(model.model.layers):
216
+ if isinstance(layer.mlp, SparseMLP):
217
+ dead_percentage = layer.mlp.dead_percentage * 100
218
+ agg_sparsity = layer.mlp.agg_sparsity * 100
219
+ ds_print(f"layer {i} sparsity: {dead_percentage:.3f}%")
220
+ ds_print(f"layer {i} agg sparsity: {agg_sparsity:.3f}%")
221
+ total_sparsity += dead_percentage
222
+ counts += 1
223
+
224
+ ds_print(f"Total sparsity: {total_sparsity/counts: .3f}%")
225
+ return total_sparsity / counts
226
+
227
+
228
+ def get_sparse_layers(model):
229
+ SparseMLP = get_mlp_class(model)
230
+ sparse_layers = [m.mlp for m in model.layers() if isinstance(m.mlp, SparseMLP)]
231
+ return sparse_layers
232
+
233
+
234
+ def get_threshold(
235
+ bin_edges: torch.tensor, histogram_counts: torch.tensor, sparsity_level: float
236
+ ): # Only for L1 Regularization
237
+ assert (
238
+ len(bin_edges.shape) == len(histogram_counts.shape) == 1
239
+ ), "bin_edges and histogram are expected to be 1-dimensional."
240
+ histogram_counts /= histogram_counts.sum()
241
+ threshold_idx = torch.searchsorted(
242
+ histogram_counts.cumsum(0), sparsity_level, side="right"
243
+ )
244
+
245
+ return bin_edges[threshold_idx]
246
+
247
+
248
+ def set_regularization_threshold(model, threshold: float = 0.1):
249
+ SparseMLP = get_mlp_class(model)
250
+ for i, layer in enumerate(model.model.layers):
251
+ if (
252
+ isinstance(layer.mlp, SparseMLP) and layer.mlp.is_stats
253
+ ): # Can set the threshold only the relevant statistics is collected.
254
+ layer.mlp.regularization_threshold = threshold # TODO: find better param
255
+
256
+
257
+ def set_sparse_threshold(model, sparsity_level: float, use_relu: bool = False):
258
+ SparseMLP = get_mlp_class(model)
259
+ for i, layer in enumerate(model.model.layers):
260
+ if (
261
+ isinstance(layer.mlp, SparseMLP) and layer.mlp.is_stats
262
+ ): # Can set the threshold only the relevant statistics is collected.
263
+ if use_relu:
264
+ layer.mlp.sparse_act_fn = nn.ReLU()
265
+ layer.mlp.use_relu = True
266
+ else:
267
+ layer.mlp.dead_threshold = get_threshold(
268
+ layer.mlp.histogram_bins,
269
+ layer.mlp.post_act_hist_counts,
270
+ sparsity_level,
271
+ )
272
+ layer.mlp.sparse_act_fn.set_new_threshold(layer.mlp.dead_threshold)
273
+ layer.mlp.regularization_threshold = (
274
+ layer.mlp.dead_threshold * 1.2
275
+ ) # TODO: find better param
276
+
277
+
278
+ # def plot_histogram(
279
+ # bin_edges,
280
+ # histogram_counts: torch.tensor,
281
+ # threshold: float = 0.5,
282
+ # title: str = "Activation Distribution",
283
+ # fig_dir: str = "figures",
284
+ # layer_index: int = 0,
285
+ # ):
286
+ # if layer_index not in [0, 15, 31]:
287
+ # return
288
+ #
289
+ # if is_mainprocess():
290
+ # torch.save(bin_edges, f"{fig_dir}/bin_edges_{layer_index}.pt")
291
+ # torch.save(histogram_counts, f"{fig_dir}/histogram_counts_{layer_index}.pt")
292
+ #
293
+ # plt.bar(
294
+ # bin_edges[:-1],
295
+ # histogram_counts,
296
+ # width=np.diff(bin_edges),
297
+ # color="#227CF6",
298
+ # )
299
+ #
300
+ # plt.axvline(x=threshold, color="#227CF6", linestyle="--", label=f"Threshold ({threshold})")
301
+ # plt.axvline(x=-threshold, color="#227CF6", linestyle="--", label=f"Threshold ({threshold})")
302
+ #
303
+ # plt.title(title)
304
+ # plt.xlabel("Activation Value")
305
+ # plt.ylabel("Frequency")
306
+ # os.makedirs(fig_dir, exist_ok=True)
307
+ # plt.savefig(f"{fig_dir}/{title}.png")
308
+ # plt.clf()
309
+
310
+
311
+ def plot_histogram(
312
+ bin_edges,
313
+ histogram_counts: torch.tensor,
314
+ threshold: float = 0.5,
315
+ title: str = "Activation Distribution",
316
+ fig_dir: str = "figures",
317
+ layer_index: int = 0,
318
+ ):
319
+ if is_mainprocess():
320
+ torch.save(bin_edges, f"{fig_dir}/bin_edges_{layer_index}.pt")
321
+ torch.save(histogram_counts, f"{fig_dir}/histogram_counts_{layer_index}.pt")
322
+
323
+ fig, ax = plt.subplots()
324
+
325
+ # Plot the bars for activations within the threshold
326
+ within_threshold_mask = (bin_edges[:-1] >= -threshold) & (bin_edges[:-1] <= threshold)
327
+ ax.bar(
328
+ bin_edges[:-1][within_threshold_mask][:-1],
329
+ histogram_counts[within_threshold_mask][:-1],
330
+ width=np.diff(bin_edges[:-1][within_threshold_mask]),
331
+ # edgecolor="black",
332
+ color="#227CF6",
333
+ alpha=0.2,
334
+ label="Within Threshold",
335
+ )
336
+
337
+ # # Plot the bars for activations outside the threshold
338
+ outside_threshold_mask = ~within_threshold_mask
339
+ ax.bar(
340
+ bin_edges[:-1][outside_threshold_mask][:-1],
341
+ histogram_counts[outside_threshold_mask][:-1],
342
+ width=np.diff(bin_edges[:-1][outside_threshold_mask]),
343
+ # edgecolor="black",
344
+ color="#227CF6",
345
+ alpha=1.0,
346
+ label="Outside Threshold",
347
+ clip_on=False,
348
+ )
349
+
350
+ # Plot the threshold lines
351
+ ax.axvline(
352
+ x=threshold,
353
+ color="#227CF6",
354
+ alpha=0.6,
355
+ linestyle="--",
356
+ label="Threshold",
357
+ )
358
+ # ax.axvline(x=-threshold, color="#227CF6", alpha=0.3, linestyle="--")
359
+ ax.axvline(x=0, color="#227CF6", alpha=0.3, linestyle="--")
360
+
361
+ # Set the title and labels
362
+ # ax.set_title(title)
363
+ ax.set_xlabel("Activation Value")
364
+ ax.set_ylabel("Frequency")
365
+
366
+ ax.set_xlim(-0.7, 0.7)
367
+
368
+ # Add legend
369
+ ax.legend()
370
+
371
+ # Create the figures directory if it doesn't exist
372
+ os.makedirs(fig_dir, exist_ok=True)
373
+
374
+ # Save the figure
375
+ plt.savefig(f"{fig_dir}/{title}.png")
376
+ # plt.show()
377
+
378
+ # Close the figure to free memory
379
+ plt.close(fig)
380
+
381
+
382
+ def plot_act(model, fig_dir: str = "figures"):
383
+ SparseMLP = get_mlp_class(model)
384
+
385
+ for i, layer in enumerate(model.model.layers):
386
+ if (
387
+ isinstance(layer.mlp, SparseMLP) and layer.mlp.is_stats
388
+ ): # Can set the threshold only the relevant statistics is collected.
389
+ # plot_title = f"Layer: {i} Pre-Activation Distribution"
390
+ # plot_histogram(layer.mlp.histogram_bins, layer.mlp.pre_act_hist_counts, plot_title, fig_dir, layer_index=i)
391
+
392
+ plot_title = f"Layer: {i} Post-Activation Absolute Distribution"
393
+ plot_histogram(
394
+ layer.mlp.histogram_bins,
395
+ layer.mlp.post_act_hist_counts,
396
+ layer.mlp.dead_threshold,
397
+ plot_title,
398
+ fig_dir,
399
+ layer_index=i,
400
+ )
401
+
402
+
403
+ def save_act_hist(
404
+ model, filename="/scr/jay/models/mistral/pre_finetune/cola_act_hist.pt"
405
+ ):
406
+ SparseMLP = get_mlp_class(model)
407
+ os.makedirs(os.path.dirname(filename), exist_ok=True)
408
+ act_dict = {}
409
+ for i, layer in enumerate(model.model.layers):
410
+ if (
411
+ isinstance(layer.mlp, SparseMLP) and layer.mlp.is_stats
412
+ ): # Can set the threshold only the relevant statistics is collected.
413
+ act_dict[i] = (
414
+ layer.mlp.histogram_bins,
415
+ layer.mlp.pre_act_hist_counts,
416
+ layer.mlp.post_act_hist_counts,
417
+ )
418
+ print("Saving activation histograms...\n\n\n")
419
+ torch.save(act_dict, filename)
420
+
421
+
422
+ def load_act_hist(
423
+ model, filename="/scr/jay/models/mistral/pre_finetune/cola_act_hist.pt"
424
+ ):
425
+ assert os.path.exists(
426
+ filename
427
+ ), f"{filename} does not exist when loading pre/post-activation histogram of SparseMistralSiluMLP."
428
+ SparseMLP = get_mlp_class(model)
429
+
430
+ print("Loading activation histograms...\n\n\n")
431
+
432
+ act_dict = torch.load(filename)
433
+ for i, layer in enumerate(model.model.layers):
434
+ if (
435
+ isinstance(layer.mlp, SparseMLP) and layer.mlp.is_stats
436
+ ): # Can set the threshold only the relevant statistics is collected.
437
+ (
438
+ layer.mlp.histogram_bins,
439
+ layer.mlp.pre_act_hist_counts,
440
+ layer.mlp.post_act_hist_counts,
441
+ ) = act_dict[i]
442
+
443
+
444
+ def enable_last_k_modules(model, start_module_idx: int):
445
+ assert 32 > start_module_idx >= 0
446
+ new_modules = []
447
+ new_idx = 0
448
+ for idx in range(start_module_idx, len(model.model.original_layers)):
449
+ module = model.model.original_layers[idx]
450
+ module.layer_idx = new_idx
451
+ module.self_attn.layer_idx = new_idx
452
+ new_modules.append(module)
453
+ new_idx += 1
454
+ print(module.layer_idx)
455
+
456
+ model.model.layers = nn.ModuleList(new_modules)
457
+
458
+
459
+ def enable_first_k_modules(model, end_module_idx: int):
460
+ assert 32 > end_module_idx >= 0
461
+ new_modules = []
462
+ new_idx = 0
463
+ for idx in range(0, end_module_idx + 1):
464
+ module = model.model.original_layers[idx]
465
+ module.layer_idx = new_idx
466
+ module.self_attn.layer_idx = new_idx
467
+ new_modules.append(module)
468
+ new_idx += 1
469
+ print(module.layer_idx)
470
+
471
+ model.model.layers = nn.ModuleList(new_modules)
472
+
473
+
474
+ # MISTRAL
475
+
476
+
477
+ class MistralSparseSiluMLP(MistralMLP):
478
+ def __init__(self, config, *args, **kwargs):
479
+ super().__init__(config)
480
+ self.swish_outputs = None
481
+ self.relu = nn.ReLU()
482
+ self.is_profile = False
483
+
484
+ self.kill_sparse_swish_outputs = False
485
+ self.dead_percentage = 0
486
+ self.is_stats = False
487
+ self.visit_counts = 0
488
+
489
+ # Hyperparameters to tune
490
+ self.dead_threshold = kwargs.pop("dead_threshold", 0)
491
+ self.use_sparse_regularization = kwargs.pop("use_sparse_regularization", True)
492
+ self.regularization_type = kwargs.pop(
493
+ "regularization_type", "L1 regularization"
494
+ )
495
+ self.regularization_threshold = kwargs.pop("regularization_threshold", 0.5)
496
+ self.use_relu = kwargs.pop("use_relu", False)
497
+ self.activation_norm = None
498
+
499
+ # Activation Histograms
500
+ self.is_collect_histogram = False
501
+ num_bins = 1000
502
+ self.histogram_bins = torch.linspace(-1, 1, num_bins - 2)
503
+ self.histogram_bins = torch.cat(
504
+ [torch.tensor([-torch.inf]), self.histogram_bins, torch.tensor([torch.inf])]
505
+ )
506
+ self.pre_act_hist_counts = torch.zeros(num_bins - 1)
507
+ self.abs_post_act_hist_counts = torch.zeros(num_bins - 1)
508
+ self.post_act_hist_counts = torch.zeros(num_bins - 1)
509
+ self.t = 0
510
+ self.count = 0
511
+ self.agg_sparsity = 0
512
+
513
+ # Sparse activation function
514
+ self.sparse_act_fn = SparseSiLU(threshold=self.dead_threshold)
515
+
516
+ def activate_stats(self, is_collect_histogram: bool = True):
517
+ self.is_stats = True
518
+ self.dead_percentage = 0
519
+ self.visit_counts = 0
520
+ self.is_collect_histogram = is_collect_histogram
521
+ self.histogram_counts = torch.zeros(2000) # .to(self.down_proj.weight.device)
522
+
523
+ def deactivate_stats(self):
524
+ self.is_stats = False
525
+
526
+ def collect_stats(self, pre_activation, post_activation):
527
+ start_time = time.time()
528
+ pre_activation = pre_activation.float().cpu().detach()
529
+ post_activation = post_activation.float().cpu().detach()
530
+ # self.histogram_bins=self.histogram_bins.to(pre_activation.device).type(pre_activation.dtype)
531
+ self.pre_act_hist_counts += torch.histogram(
532
+ pre_activation, bins=self.histogram_bins
533
+ )[0]
534
+ self.post_act_hist_counts += torch.histogram(
535
+ torch.abs(post_activation), bins=self.histogram_bins
536
+ )[0]
537
+ # self.post_act_hist_counts += torch.histogram(post_activation, bins=self.histogram_bins)[0]
538
+ self.t += time.time() - start_time
539
+ # if self.visit_counts % 30 == 0:
540
+ # print(f"Time taken to collect stats: {self.t}s.")
541
+
542
+ def forward(
543
+ self,
544
+ x,
545
+ sp_mask: torch.tensor = None,
546
+ ):
547
+ """
548
+ If kill_sparse_swish_outputs is set to False, this layer functions exactly like a normal MLP layer.
549
+ """
550
+ if sp_mask != None: # When sparse mask is given
551
+ return self.down_proj(
552
+ self.sparse_act_fn(self.gate_proj(x) * sp_mask) * self.up_proj(x)
553
+ ) # Todo: This doesn't accelerate runtime (instead slowing down)
554
+
555
+ if self.is_profile:
556
+ if x.shape[1] == 1:
557
+ if self.sp_method == 1:
558
+ return flash_gemv.flag_gemv_gemv_inner_bf16(
559
+ x,
560
+ self.gate_proj.weight,
561
+ self.up_proj.weight,
562
+ self.down_proj.weight,
563
+ self.dead_threshold,
564
+ )
565
+ elif self.sp_method == 2:
566
+ return flash_gemv.gemv_gemv_triton(
567
+ x,
568
+ self.act_fn(self.gate_proj(x)),
569
+ self.up_proj.weight,
570
+ self.wdown_t,
571
+ self.dead_threshold,
572
+ )
573
+ else:
574
+ post_act = self.act_fn(self.gate_proj(x))
575
+ dead_neurons = post_act.abs() <= self.dead_threshold
576
+ post_act[dead_neurons] = 0
577
+ return self.down_proj(post_act * self.up_proj(x))
578
+ else:
579
+ post_act = self.act_fn(self.gate_proj(x))
580
+ dead_neurons = post_act.abs() <= self.dead_threshold
581
+ post_act[dead_neurons] = 0
582
+ return self.down_proj(post_act * self.up_proj(x))
583
+
584
+ elif self.use_relu:
585
+ post_act = self.relu(self.gate_proj(x))
586
+ self.count += 1
587
+ if self.count <= 1:
588
+ print("USING RELU!!!!")
589
+
590
+ if self.is_stats:
591
+ dead_neurons = post_act == 0
592
+ dead_percentage = dead_neurons.float().mean()
593
+ agg_sparsity = dead_neurons.all(dim=0).float().mean()
594
+
595
+ self.dead_percentage = (
596
+ self.dead_percentage * self.visit_counts + dead_percentage
597
+ ) / (self.visit_counts + 1)
598
+ self.agg_sparsity = (
599
+ self.agg_sparsity * self.visit_counts + agg_sparsity
600
+ ) / (self.visit_counts + 1)
601
+ self.visit_counts += 1
602
+
603
+ return self.down_proj(post_act * self.up_proj(x))
604
+
605
+ else:
606
+ self.count += 1
607
+ if self.count <= 1:
608
+ ds_print("USING SparseSILU!!!!")
609
+ pre_act = self.gate_proj(x)
610
+ post_act = self.act_fn(pre_act)
611
+ if self.kill_sparse_swish_outputs:
612
+ dead_neurons = post_act.abs() <= self.dead_threshold
613
+ # print("pre act sparsity: ", (pre_act==0).float().mean())
614
+
615
+ dead_percentage = dead_neurons.float().mean()
616
+ agg_sparsity = dead_neurons.all(dim=0).float().mean()
617
+
618
+ if self.is_stats:
619
+ self.dead_percentage = (
620
+ self.dead_percentage * self.visit_counts + dead_percentage
621
+ ) / (self.visit_counts + 1)
622
+ self.agg_sparsity = (
623
+ self.agg_sparsity * self.visit_counts + agg_sparsity
624
+ ) / (self.visit_counts + 1)
625
+ self.visit_counts += 1
626
+
627
+ self.a = dead_percentage
628
+
629
+ # Collect histogram stats
630
+ if (
631
+ self.is_collect_histogram
632
+ and pre_act.eq(0).float().mean() < 0.99
633
+ ): # Padded dataset
634
+ self.collect_stats(pre_act, post_act)
635
+
636
+ if self.count <= 1:
637
+ ds_print("KILL!")
638
+ post_act[dead_neurons] = 0
639
+
640
+ out = self.down_proj(post_act * self.up_proj(x))
641
+ if self.use_sparse_regularization:
642
+ if self.regularization_type == "L1 regularization":
643
+ self.activation_norm = torch.abs(post_act)[
644
+ torch.abs(post_act) < self.regularization_threshold
645
+ ].mean()
646
+ elif self.regularization_type == "L2 regularization":
647
+ self.activation_norm = torch.sqrt(
648
+ torch.square(post_act)[
649
+ torch.abs(post_act) < self.regularization_threshold
650
+ ]
651
+ ).mean()
652
+
653
+ return out
654
+
655
+
656
+ class SparseMistralDecoderLayer(MistralDecoderLayer):
657
+ def __init__(
658
+ self,
659
+ config: MistralConfig,
660
+ layer_idx: int,
661
+ decoder_layer: MistralDecoderLayer,
662
+ init_svd: bool = True,
663
+ *args,
664
+ **kwargs,
665
+ ):
666
+ assert isinstance(
667
+ decoder_layer.mlp, MistralSparseSiluMLP
668
+ ), f"{type(decoder_layer.mlp)} should MistralSparseSiluMLP."
669
+
670
+ super().__init__(config, layer_idx)
671
+ self.hidden_size = config.hidden_size
672
+ self.intermediate_size = config.intermediate_size
673
+
674
+ self.init_svd = init_svd
675
+ self.self_attn = decoder_layer.self_attn
676
+
677
+ self.mlp = decoder_layer.mlp
678
+ self.input_layernorm = decoder_layer.input_layernorm
679
+ self.post_attention_layernorm = decoder_layer.post_attention_layernorm
680
+
681
+ # Sparse predictor for mlp (initialized with SVD decomposed matrix)
682
+ self.low_rank = kwargs.pop("low_rank", 64)
683
+ self.sparse_act_func = decoder_layer.mlp.sparse_act_fn
684
+
685
+ print(
686
+ f"Setting {layer_idx}th mlp layer's sparse predictor... svd init: {init_svd}"
687
+ )
688
+ self.sp_mlp = low_rank_approximation(
689
+ decoder_layer.mlp.gate_proj,
690
+ act_func=self.sparse_act_func,
691
+ init_svd=init_svd,
692
+ )
693
+ self.use_async = kwargs.pop("use_async", False)
694
+ self.use_sparse_predictor = False
695
+ self.distill_loss = None
696
+
697
+ def forward(
698
+ self,
699
+ hidden_states: torch.Tensor,
700
+ attention_mask: Optional[torch.Tensor] = None,
701
+ position_ids: Optional[torch.LongTensor] = None,
702
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
703
+ output_attentions: Optional[bool] = False,
704
+ use_cache: Optional[bool] = False,
705
+ **kwargs,
706
+ ) -> Tuple[
707
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
708
+ ]:
709
+ print("hidden_states shape: ", hidden_states.shape)
710
+ if "padding_mask" in kwargs:
711
+ warnings.warn(
712
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
713
+ )
714
+
715
+ residual = hidden_states
716
+ sp_mask = None
717
+
718
+ if self.use_async:
719
+ sp_mask = self.sp_mlp(hidden_states)
720
+
721
+ hidden_states = self.input_layernorm(hidden_states)
722
+
723
+ # Self Attention
724
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
725
+ hidden_states=hidden_states,
726
+ attention_mask=attention_mask,
727
+ position_ids=position_ids,
728
+ past_key_value=past_key_value,
729
+ output_attentions=output_attentions,
730
+ use_cache=use_cache,
731
+ )
732
+ hidden_states = residual + hidden_states
733
+
734
+ # Fully Connected
735
+ residual = hidden_states
736
+ hidden_states = self.post_attention_layernorm(hidden_states)
737
+
738
+ if not self.use_async:
739
+ sp_mask = self.sp_mlp(hidden_states)
740
+
741
+ # Compute distillation loss
742
+ gating_output = self.mlp.sparse_act_fn(self.mlp.gate_proj(hidden_states))
743
+ loss_func = MSELoss()
744
+ self.distill_loss = loss_func(sp_mask, gating_output)
745
+
746
+ # Convert sp mask into binary form
747
+ sp_mask = sp_mask > 0
748
+
749
+ if self.training:
750
+ sp_mask = None
751
+ # if not self.use_sparse_predictor:
752
+ # sp_mask = None
753
+
754
+ hidden_states = self.mlp(hidden_states, sp_mask)
755
+ hidden_states = residual + hidden_states
756
+
757
+ outputs = (hidden_states,)
758
+
759
+ if output_attentions:
760
+ outputs += (self_attn_weights,)
761
+
762
+ if use_cache:
763
+ outputs += (present_key_value,)
764
+
765
+ return outputs
766
+
767
+
768
+ class SparseMistralConfig(MistralConfig):
769
+ model_type = "sparse_mistral"
770
+
771
+ def __init__(self, **kwargs):
772
+ super().__init__(**kwargs)
773
+
774
+
775
+ class SparseMistralforCausalLM(MistralForCausalLM):
776
+ config_class = SparseMistralConfig
777
+
778
+ def __init__(self, config):
779
+ super().__init__(config)
780
+ self.config = config
781
+ if config.use_sparse_model:
782
+ self.apply_sparse_mlp()
783
+ if config.thresholds is not None:
784
+ for idx, m in enumerate(self.model.layers):
785
+ if isinstance(m.mlp, MistralSparseSiluMLP):
786
+ m.mlp.dead_threshold = config.thresholds[idx]
787
+ m.mlp.sparse_act_fn.set_new_threshold(m.mlp.dead_threshold)
788
+ m.mlp.kill_sparse_swish_outputs = True
789
+ m.mlp.use_relu = config.use_relu
790
+ if config.use_sparse_predictor:
791
+ self.apply_sparse_predictor(init_svd=config.init_svd)
792
+
793
+ def apply_sparse_mlp(self):
794
+ apply_sparse_silu_mlp(
795
+ self,
796
+ config=self.config,
797
+ use_sparse_regularization=self.config.use_sparse_regularization,
798
+ )
799
+
800
+ def apply_sparse_predictor(self, init_svd: bool = True):
801
+ apply_sparse_decoder_layer(self, config=self.config, init_svd=init_svd)
802
+
803
+
804
+ # LLAMA
805
+
806
+
807
+ class SparseLlamaConfig(LlamaConfig):
808
+ model_type = "sparse_llama"
809
+
810
+ def __init__(self, **kwargs):
811
+ super().__init__(**kwargs)
812
+
813
+
814
+ class SparseLlamaForCausalLM(LlamaForCausalLM):
815
+ config_class = SparseLlamaConfig
816
+
817
+ def __init__(self, config):
818
+ super().__init__(config)
819
+ self.config = config
820
+ if config.use_sparse_model:
821
+ self.apply_sparse_mlp()
822
+ if config.thresholds is not None:
823
+ for idx, m in enumerate(self.model.layers):
824
+ if isinstance(m.mlp, LlamaSparseSiluMLP):
825
+ m.mlp.dead_threshold = config.thresholds[idx]
826
+ m.mlp.sparse_act_fn.set_new_threshold(m.mlp.dead_threshold)
827
+ m.mlp.kill_sparse_swish_outputs = True
828
+ m.mlp.use_relu = config.use_relu
829
+ if config.use_sparse_predictor:
830
+ self.apply_sparse_predictor(init_svd=config.init_svd)
831
+
832
+ def apply_sparse_mlp(self):
833
+ apply_sparse_silu_mlp(
834
+ self,
835
+ config=self.config,
836
+ use_sparse_regularization=self.config.use_sparse_regularization,
837
+ )
838
+
839
+ def apply_sparse_predictor(self, init_svd: bool = True):
840
+ apply_sparse_decoder_layer(self, config=self.config, init_svd=init_svd)
841
+
842
+
843
+ class LlamaSparseSiluMLP(LlamaMLP):
844
+ def __init__(self, config, *args, **kwargs):
845
+ super().__init__(config)
846
+ self.swish_outputs = None
847
+ self.relu = nn.ReLU()
848
+ self.is_profile = False
849
+
850
+ self.kill_sparse_swish_outputs = False
851
+ self.dead_percentage = 0
852
+ self.is_stats = False
853
+ self.visit_counts = 0
854
+
855
+ # Hyperparameters to tune
856
+ self.dead_threshold = kwargs.pop("dead_threshold", 0)
857
+ self.use_sparse_regularization = kwargs.pop("use_sparse_regularization", True)
858
+ self.regularization_type = kwargs.pop(
859
+ "regularization_type", "L1 regularization"
860
+ )
861
+ self.regularization_threshold = kwargs.pop("regularization_threshold", 0.5)
862
+ self.use_relu = kwargs.pop("use_relu", False)
863
+ self.activation_norm = None
864
+
865
+ # Activation Histograms
866
+ self.is_collect_histogram = False
867
+ num_bins = 1000
868
+ self.histogram_bins = torch.linspace(-1, 1, num_bins - 2)
869
+ self.histogram_bins = torch.cat(
870
+ [torch.tensor([-torch.inf]), self.histogram_bins, torch.tensor([torch.inf])]
871
+ )
872
+ self.pre_act_hist_counts = torch.zeros(num_bins - 1)
873
+ self.abs_post_act_hist_counts = torch.zeros(num_bins - 1)
874
+ self.post_act_hist_counts = torch.zeros(num_bins - 1)
875
+ self.t = 0
876
+ self.count = 0
877
+ self.agg_sparsity = 0
878
+
879
+ # Sparse activation function
880
+ self.sparse_act_fn = SparseSiLU(threshold=self.dead_threshold)
881
+
882
+ def activate_stats(self, is_collect_histogram: bool = True):
883
+ self.is_stats = True
884
+ self.dead_percentage = 0
885
+ self.visit_counts = 0
886
+ self.is_collect_histogram = is_collect_histogram
887
+ self.histogram_counts = torch.zeros(2000) # .to(self.down_proj.weight.device)
888
+
889
+ def deactivate_stats(self):
890
+ self.is_stats = False
891
+
892
+ def collect_stats(self, pre_activation, post_activation):
893
+ start_time = time.time()
894
+ pre_activation = pre_activation.float().cpu().detach()
895
+ post_activation = post_activation.float().cpu().detach()
896
+ # self.histogram_bins=self.histogram_bins.to(pre_activation.device).type(pre_activation.dtype)
897
+ self.pre_act_hist_counts += torch.histogram(
898
+ pre_activation, bins=self.histogram_bins
899
+ )[0]
900
+ self.post_act_hist_counts += torch.histogram(
901
+ torch.abs(post_activation), bins=self.histogram_bins
902
+ )[0]
903
+ # self.post_act_hist_counts += torch.histogram(post_activation, bins=self.histogram_bins)[0]
904
+ self.t += time.time() - start_time
905
+ # if self.visit_counts % 30 == 0:
906
+ # print(f"Time taken to collect stats: {self.t}s.")
907
+
908
+ def forward(
909
+ self,
910
+ x,
911
+ sp_mask: torch.tensor = None,
912
+ ):
913
+ """
914
+ If kill_sparse_swish_outputs is set to False, this layer functions exactly like a normal MLP layer.
915
+ """
916
+ if sp_mask != None: # When sparse mask is given
917
+ return self.down_proj(
918
+ self.sparse_act_fn(self.gate_proj(x) * sp_mask) * self.up_proj(x)
919
+ ) # Todo: This doesn't accelerate runtime (instead slowing down)
920
+
921
+ if self.is_profile:
922
+ if x.shape[1] == 1:
923
+ if self.sp_method == 1:
924
+ return flash_gemv.flag_gemv_gemv_inner_bf16(
925
+ x,
926
+ self.gate_proj.weight,
927
+ self.up_proj.weight,
928
+ self.down_proj.weight,
929
+ self.dead_threshold,
930
+ )
931
+ elif self.sp_method == 2:
932
+ return flash_gemv.gemv_gemv_triton(
933
+ x,
934
+ self.act_fn(self.gate_proj(x)),
935
+ self.up_proj.weight,
936
+ self.wdown_t,
937
+ self.dead_threshold,
938
+ )
939
+ else:
940
+ post_act = self.act_fn(self.gate_proj(x))
941
+ dead_neurons = post_act.abs() <= self.dead_threshold
942
+ post_act[dead_neurons] = 0
943
+ return self.down_proj(post_act * self.up_proj(x))
944
+ else:
945
+ post_act = self.act_fn(self.gate_proj(x))
946
+ dead_neurons = post_act.abs() <= self.dead_threshold
947
+ post_act[dead_neurons] = 0
948
+ return self.down_proj(post_act * self.up_proj(x))
949
+
950
+ elif self.use_relu:
951
+ post_act = self.relu(self.gate_proj(x))
952
+ self.count += 1
953
+
954
+ if self.is_stats:
955
+ dead_neurons = post_act == 0
956
+ dead_percentage = dead_neurons.float().mean()
957
+ agg_sparsity = dead_neurons.all(dim=0).float().mean()
958
+
959
+ self.dead_percentage = (
960
+ self.dead_percentage * self.visit_counts + dead_percentage
961
+ ) / (self.visit_counts + 1)
962
+ self.agg_sparsity = (
963
+ self.agg_sparsity * self.visit_counts + agg_sparsity
964
+ ) / (self.visit_counts + 1)
965
+ self.visit_counts += 1
966
+
967
+ return self.down_proj(post_act * self.up_proj(x))
968
+
969
+ else:
970
+ self.count += 1
971
+ pre_act = self.gate_proj(x)
972
+ post_act = self.act_fn(pre_act)
973
+ if self.kill_sparse_swish_outputs:
974
+ dead_neurons = post_act.abs() <= self.dead_threshold
975
+ dead_percentage = dead_neurons.float().mean()
976
+ agg_sparsity = dead_neurons.all(dim=0).float().mean()
977
+
978
+ if self.is_stats:
979
+ self.dead_percentage = (
980
+ self.dead_percentage * self.visit_counts + dead_percentage
981
+ ) / (self.visit_counts + 1)
982
+ self.agg_sparsity = (
983
+ self.agg_sparsity * self.visit_counts + agg_sparsity
984
+ ) / (self.visit_counts + 1)
985
+ self.visit_counts += 1
986
+
987
+ self.a = dead_percentage
988
+
989
+ # Collect histogram stats
990
+ # if self.is_collect_histogram and pre_act.eq(0).float().mean() < 0.99: # Padded dataset
991
+ if self.is_collect_histogram: # Padded dataset
992
+ self.collect_stats(pre_act, post_act)
993
+
994
+ if self.count <= 1:
995
+ ds_print("KILL!")
996
+ post_act[dead_neurons] = 0
997
+
998
+ out = self.down_proj(post_act * self.up_proj(x))
999
+ if self.use_sparse_regularization:
1000
+ if self.regularization_type == "L1 regularization":
1001
+ self.activation_norm = torch.abs(post_act)[
1002
+ torch.abs(post_act) < self.regularization_threshold
1003
+ ].mean()
1004
+ elif self.regularization_type == "L2 regularization":
1005
+ self.activation_norm = torch.sqrt(
1006
+ torch.square(post_act)[
1007
+ torch.abs(post_act) < self.regularization_threshold
1008
+ ]
1009
+ ).mean()
1010
+
1011
+ return out
1012
+
1013
+
1014
+ class LlamaSparseDecoderLayer(LlamaDecoderLayer):
1015
+ def __init__(
1016
+ self,
1017
+ config: LlamaConfig,
1018
+ layer_idx: int,
1019
+ decoder_layer: LlamaDecoderLayer,
1020
+ init_svd: bool = True,
1021
+ *args,
1022
+ **kwargs,
1023
+ ):
1024
+ assert isinstance(
1025
+ decoder_layer.mlp, LlamaSparseSiluMLP
1026
+ ), f"{type(decoder_layer.mlp)} should be LlamaSparseSiluMLP."
1027
+
1028
+ super().__init__(config, layer_idx)
1029
+ self.hidden_size = config.hidden_size
1030
+ self.intermediate_size = config.intermediate_size
1031
+
1032
+ self.init_svd = init_svd
1033
+ self.self_attn = decoder_layer.self_attn
1034
+
1035
+ self.mlp = decoder_layer.mlp
1036
+ self.input_layernorm = decoder_layer.input_layernorm
1037
+ self.post_attention_layernorm = decoder_layer.post_attention_layernorm
1038
+
1039
+ # Sparse predictor for mlp (initialized with SVD decomposed matrix)
1040
+ self.low_rank = kwargs.pop("low_rank", 64)
1041
+ self.sparse_act_func = decoder_layer.mlp.sparse_act_fn
1042
+
1043
+ print(
1044
+ f"Setting {layer_idx}th mlp layer's sparse predictor... svd init: {init_svd}"
1045
+ )
1046
+ self.sp_mlp = low_rank_approximation(
1047
+ decoder_layer.mlp.gate_proj,
1048
+ act_func=self.sparse_act_func,
1049
+ init_svd=init_svd,
1050
+ )
1051
+ self.use_async = kwargs.pop("use_async", False)
1052
+ self.use_sparse_predictor = False
1053
+ self.distill_loss = None
1054
+
1055
+ def forward(
1056
+ self,
1057
+ hidden_states: torch.Tensor,
1058
+ attention_mask: Optional[torch.Tensor] = None,
1059
+ position_ids: Optional[torch.LongTensor] = None,
1060
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1061
+ output_attentions: Optional[bool] = False,
1062
+ use_cache: Optional[bool] = False,
1063
+ **kwargs,
1064
+ ) -> Tuple[
1065
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
1066
+ ]:
1067
+ print("hidden_states shape: ", hidden_states.shape)
1068
+ if "padding_mask" in kwargs:
1069
+ warnings.warn(
1070
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1071
+ )
1072
+
1073
+ residual = hidden_states
1074
+ sp_mask = None
1075
+
1076
+ if self.use_async:
1077
+ sp_mask = self.sp_mlp(hidden_states)
1078
+
1079
+ hidden_states = self.input_layernorm(hidden_states)
1080
+
1081
+ # Self Attention
1082
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1083
+ hidden_states=hidden_states,
1084
+ attention_mask=attention_mask,
1085
+ position_ids=position_ids,
1086
+ past_key_value=past_key_value,
1087
+ output_attentions=output_attentions,
1088
+ use_cache=use_cache,
1089
+ **kwargs,
1090
+ )
1091
+ hidden_states = residual + hidden_states
1092
+
1093
+ # Fully Connected
1094
+ residual = hidden_states
1095
+ hidden_states = self.post_attention_layernorm(hidden_states)
1096
+
1097
+ if not self.use_async:
1098
+ sp_mask = self.sp_mlp(hidden_states)
1099
+
1100
+ # Compute distillation loss
1101
+ gating_output = self.mlp.sparse_act_fn(self.mlp.gate_proj(hidden_states))
1102
+ loss_func = MSELoss()
1103
+ self.distill_loss = loss_func(sp_mask, gating_output)
1104
+
1105
+ # Convert sp mask into binary form
1106
+ sp_mask = sp_mask > 0
1107
+
1108
+ if self.training:
1109
+ sp_mask = None
1110
+ # if not self.use_sparse_predictor:
1111
+ # sp_mask = None
1112
+
1113
+ hidden_states = self.mlp(hidden_states, sp_mask)
1114
+ hidden_states = residual + hidden_states
1115
+
1116
+ outputs = (hidden_states,)
1117
+
1118
+ if output_attentions:
1119
+ outputs += (self_attn_weights,)
1120
+
1121
+ if use_cache:
1122
+ outputs += (present_key_value,)
1123
+
1124
+ return outputs
1125
+
1126
+
1127
+ # Callbacks
1128
+
1129
+
1130
+ class GracefulRegularizationScheduler(TrainerCallback):
1131
+ def __init__(
1132
+ self,
1133
+ num_warmup_steps=40,
1134
+ is_enabled: bool = False,
1135
+ model_name: str = "mistral",
1136
+ test_dataset: Dataset = None,
1137
+ targeted_sparsity: float = 0.5,
1138
+ keep_regularization_with_kill: bool = False,
1139
+ ):
1140
+ """Scheduler for regularizing the model first before applying the dead threshold.
1141
+
1142
+ :param num_warmup_steps: number of training steps required to reach the dead threshold, defaults to 40
1143
+ :param increment_ratio: by how much to increase the dead threshold.
1144
+ For example, 0.5 means "increase the threshold by 0.5 * desired threshold
1145
+ """
1146
+ self.num_warmup_steps = num_warmup_steps
1147
+ self.is_enabled = is_enabled
1148
+ self.model_name = model_name
1149
+ self.test_dataset = test_dataset
1150
+ self.targeted_sparsity = targeted_sparsity
1151
+ self.keep_regularization_with_kill = keep_regularization_with_kill
1152
+ self.act_hist_path = (
1153
+ f"/scr/lukeai/histograms/warm_up_reg_{targeted_sparsity}/act_hist.pt"
1154
+ )
1155
+ if self.is_enabled:
1156
+ print("GracefulRegularizationScheduler is enabled.")
1157
+ self.trainer = None
1158
+
1159
+ def set_trainer(self, trainer):
1160
+ self.trainer = trainer
1161
+
1162
+ def on_step_end(self, args, state, control, **kwargs):
1163
+ if not self.is_enabled:
1164
+ return
1165
+
1166
+ model = kwargs["model"]
1167
+ if isinstance(model, PeftModel):
1168
+ base_model = model.get_base_model()
1169
+ else:
1170
+ base_model = model
1171
+
1172
+ if state.global_step == 1:
1173
+ ds_print("Setting an initial reg threshold to 0.1")
1174
+ set_regularization_threshold(base_model, 0.1)
1175
+ disable_sparse_silu(base_model)
1176
+
1177
+ if state.global_step == self.num_warmup_steps:
1178
+ activate_stats(base_model)
1179
+ enable_sparse_silu(base_model)
1180
+ self.trainer.evaluate()
1181
+ save_act_hist(base_model, self.act_hist_path)
1182
+ set_sparse_threshold(base_model, self.targeted_sparsity, False)
1183
+ deactivate_stats(base_model)
1184
+ self.trainer.use_sparse_regularization = self.keep_regularization_with_kill
1185
+ print_dead_neuron_stats(model.get_base_model())
1186
+
1187
+
1188
+ class GradualSparsificationScheduler(TrainerCallback):
1189
+ def __init__(
1190
+ self,
1191
+ num_warmup_steps=40,
1192
+ increment_ratio=0.5,
1193
+ is_enabled: bool = False,
1194
+ model_name: str = "mistral",
1195
+ ):
1196
+ """Scheduler for gradually increasing a dead threshold until it reaches the desired threshold.
1197
+
1198
+ :param num_warmup_steps: number of training steps required to reach the dead threshold, defaults to 40
1199
+ :param increment_ratio: by how much to increase the dead threshold.
1200
+ For example, 0.5 means "increase the threshold by 0.5 * desired threshold
1201
+ """
1202
+ self.num_warmup_steps = num_warmup_steps
1203
+ self.increment_ratio = increment_ratio
1204
+ self.step_size = int(num_warmup_steps * increment_ratio)
1205
+ self.is_enabled = is_enabled
1206
+ self.model_name = model_name
1207
+ self.model_type = get_model_type(model_name)
1208
+ self.mlp_type = (
1209
+ MistralSparseSiluMLP if self.model_type == MISTRAL else LlamaSparseSiluMLP
1210
+ )
1211
+
1212
+ def on_step_end(self, args, state, control, **kwargs):
1213
+ model = kwargs["model"]
1214
+
1215
+ if not self.is_enabled:
1216
+ if state.global_step <= 10:
1217
+ for module in model.modules():
1218
+ if isinstance(module, self.mlp_type):
1219
+ module.current_dead_threshold = module.dead_threshold
1220
+ return
1221
+
1222
+ current_dead_threshold = 0
1223
+ desired_dead_threshold = 0
1224
+
1225
+ if is_mainprocess():
1226
+ ds_print(state.global_step)
1227
+
1228
+ if state.global_step % self.step_size == 2:
1229
+ for module in model.modules():
1230
+ if isinstance(module, self.mlp_type):
1231
+ desired_dead_threshold = copy.deepcopy(module.dead_threshold)
1232
+ current_dead_threshold = module.current_dead_threshold
1233
+ current_dead_threshold += (
1234
+ self.increment_ratio * desired_dead_threshold
1235
+ )
1236
+ module.current_dead_threshold = min(
1237
+ desired_dead_threshold, current_dead_threshold
1238
+ )
1239
+
1240
+ if is_running_deepspeed and is_mainprocess():
1241
+ ds_print(
1242
+ state.global_step,
1243
+ current_dead_threshold,
1244
+ desired_dead_threshold,
1245
+ )
1246
+
1247
+ if state.global_step % 2000 == 0:
1248
+ if is_running_deepspeed and is_mainprocess():
1249
+ ds_print(
1250
+ f"Saving to /matx/u/lukeai/{self.model_name}_{state.global_step - 2}.pt",
1251
+ )
1252
+ torch.save(
1253
+ model.state_dict(),
1254
+ f"/matx/u/lukeai/{self.model_name}_{state.global_step - 2}.pt",
1255
+ )
1256
+
1257
+
1258
+ # Trainer
1259
+
1260
+
1261
+ class SparseTrainer(Trainer):
1262
+ def __init__(self, *args, **kwargs):
1263
+ self.regularization_coefficient = kwargs.pop("regularization_coefficient", 10)
1264
+ self.use_sparse_regularization = kwargs.pop("use_sparse_regularization", False)
1265
+ self.use_spm_loss = False
1266
+ self.freeze_original_weights = False
1267
+ self.regularization_type = kwargs.pop(
1268
+ "regularization_type", "L1 positive activation"
1269
+ )
1270
+ assert self.regularization_type in [
1271
+ "L2 activation",
1272
+ "L1 positive activation",
1273
+ ], f"Invalid regularization type: {self.regularization_type}"
1274
+ self.sparse_layers = []
1275
+ self.sparse_decoder_layers = []
1276
+ super(SparseTrainer, self).__init__(*args, **kwargs)
1277
+
1278
+ def initialize_sparse_silu_layers(self, model):
1279
+ SparseMLP = get_mlp_class(model)
1280
+ self.sparse_layers = [m for m in model.modules() if isinstance(m, SparseMLP)]
1281
+
1282
+ def initialize_sparse_decoder_layers(self, model):
1283
+ SparseDecoder = get_decoder_class(model)
1284
+ self.sparse_decoder_layers = [
1285
+ m for m in model.modules() if isinstance(m, SparseDecoder)
1286
+ ]
1287
+
1288
+ def training_step(
1289
+ self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]]
1290
+ ) -> torch.Tensor:
1291
+ """
1292
+ Override the huggingface's training_step function to add a regularization term.
1293
+ A regularization term is computed with intermediate values, which are freed after "backward()."
1294
+ You need to set `retain_graph=True` inside `backward` function to keep the values.
1295
+ """
1296
+ model.train()
1297
+ inputs = self._prepare_inputs(inputs)
1298
+
1299
+ with self.compute_loss_context_manager():
1300
+ loss = self.compute_loss(model, inputs)
1301
+
1302
+ if self.args.n_gpu > 1:
1303
+ loss = loss.mean() # mean() to average on multi-gpu parallel training
1304
+
1305
+ if not self.freeze_original_weights:
1306
+ if loss is not None:
1307
+ self.accelerator.backward(loss, retain_graph=True)
1308
+
1309
+ if self.use_sparse_regularization:
1310
+ regularization_loss = self.compute_regularization(model)
1311
+ if self.args.n_gpu > 1:
1312
+ regularization_loss = regularization_loss.mean()
1313
+ if regularization_loss is not None:
1314
+ self.accelerator.backward(regularization_loss, retain_graph=True)
1315
+ loss += regularization_loss
1316
+
1317
+ if self.use_spm_loss:
1318
+ spm_loss = self.compute_spm_loss(model)
1319
+ if self.args.n_gpu > 1:
1320
+ spm_loss = spm_loss.mean()
1321
+ if spm_loss is not None:
1322
+ self.accelerator.backward(spm_loss, retain_graph=False)
1323
+ loss += spm_loss
1324
+
1325
+ return loss.detach() / self.args.gradient_accumulation_steps
1326
+
1327
+ def compute_regularization(self, model):
1328
+ """
1329
+ Compute a sparse regularization loss for SiLU
1330
+ """
1331
+ loss = 0
1332
+ if len(self.sparse_layers) == 0:
1333
+ self.initialize_sparse_silu_layers(model)
1334
+ num_layers = len(self.sparse_layers)
1335
+
1336
+ for module in self.sparse_layers:
1337
+ if module.activation_norm is not None:
1338
+ loss += module.activation_norm
1339
+
1340
+ loss /= num_layers
1341
+ loss *= self.regularization_coefficient
1342
+
1343
+ if self.state.global_step % 20 == 0 and loss != 0:
1344
+ print("Negative relularizer loss: ", loss.item())
1345
+ return loss
1346
+
1347
+ def compute_spm_loss(self, model):
1348
+ loss = 0
1349
+ if len(self.sparse_decoder_layers) == 0:
1350
+ self.initialize_sparse_decoder_layers(model)
1351
+ for module in self.sparse_decoder_layers:
1352
+ if module.distill_loss != None:
1353
+ loss += module.distill_loss
1354
+ if self.state.global_step % 20 == 0 and loss != 0:
1355
+ print("Sparse Predictor Distillation loss: ", loss.item())
1356
+ return loss