lukeleeai commited on
Commit
cfbccf5
1 Parent(s): 4fe4c48

Training in progress, step 250

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