lukeleeai commited on
Commit
1322f51
1 Parent(s): f392c3a

Training in progress, step 200

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