lukeleeai commited on
Commit
de9dd17
·
verified ·
1 Parent(s): 1276cfc

Training in progress, step 10

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