vxbrandon commited on
Commit
b5aa62d
·
verified ·
1 Parent(s): 9bff0c3

End of training

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