lukeleeai commited on
Commit
a2ef23c
·
verified ·
1 Parent(s): a404c9d

End of training

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