vxbrandon commited on
Commit
dae4378
1 Parent(s): 5863b60

Training in progress, step 100

Browse files
adapter_config.json CHANGED
@@ -19,11 +19,11 @@
19
  "rank_pattern": {},
20
  "revision": null,
21
  "target_modules": [
 
 
22
  "q_proj",
23
- "gate_proj",
24
  "down_proj",
25
- "v_proj",
26
- "up_proj"
27
  ],
28
  "task_type": "CAUSAL_LM"
29
  }
 
19
  "rank_pattern": {},
20
  "revision": null,
21
  "target_modules": [
22
+ "up_proj",
23
+ "v_proj",
24
  "q_proj",
 
25
  "down_proj",
26
+ "gate_proj"
 
27
  ],
28
  "task_type": "CAUSAL_LM"
29
  }
adapter_model.safetensors CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:dd58caed676f51b9b3975c8256522fdee32177eea04d2f5c78b6c09d6500950d
3
  size 281061608
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:36d92737c99e0cc4c8e399fcc05b32f7b77e0554da0aa91d26bbc92797f59555
3
  size 281061608
config.json ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "mistralai/Mistral-7B-v0.1",
3
+ "architectures": [
4
+ "SparseMistralforCausalLM"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "sparsification_sftt.SparseMistralConfig",
9
+ "AutoModelForCausalLM": "sparsification_sftt.SparseMistralforCausalLM"
10
+ },
11
+ "bos_token_id": 1,
12
+ "cut_pre_attn": false,
13
+ "cut_pre_mlp": false,
14
+ "eos_token_id": 2,
15
+ "hidden_act": "silu",
16
+ "hidden_size": 4096,
17
+ "initializer_range": 0.02,
18
+ "intermediate_size": 14336,
19
+ "max_position_embeddings": 32768,
20
+ "model_type": "sparse_mistral",
21
+ "num_attention_heads": 32,
22
+ "num_hidden_layers": 32,
23
+ "num_key_value_heads": 8,
24
+ "rms_norm_eps": 1e-05,
25
+ "rope_theta": 10000.0,
26
+ "sliding_window": 4096,
27
+ "thresholds": [
28
+ 0.06619857996702194,
29
+ 0.09027080237865448,
30
+ 0.1103309765458107,
31
+ 0.13841523230075836,
32
+ 0.1464392989873886,
33
+ 0.1464392989873886,
34
+ 0.15847541391849518,
35
+ 0.15446338057518005,
36
+ 0.17051151394844055,
37
+ 0.1945837438106537,
38
+ 0.20260781049728394,
39
+ 0.2146439254283905,
40
+ 0.2146439254283905,
41
+ 0.230692058801651,
42
+ 0.22668002545833588,
43
+ 0.230692058801651,
44
+ 0.21865595877170563,
45
+ 0.24272817373275757,
46
+ 0.2467402070760727,
47
+ 0.2467402070760727,
48
+ 0.230692058801651,
49
+ 0.20260781049728394,
50
+ 0.2467402070760727,
51
+ 0.2507522404193878,
52
+ 0.22668002545833588,
53
+ 0.23871614038944244,
54
+ 0.2668004035949707,
55
+ 0.27482447028160095,
56
+ 0.30692073702812195,
57
+ 0.4393179416656494,
58
+ 0.5757271647453308,
59
+ 0.7642928957939148
60
+ ],
61
+ "tie_word_embeddings": false,
62
+ "torch_dtype": "bfloat16",
63
+ "transformers_version": "4.36.2",
64
+ "use_cache": false,
65
+ "use_relu": false,
66
+ "use_resilu": false,
67
+ "use_sparse_model": true,
68
+ "use_sparse_predictor": false,
69
+ "use_sparse_regularization": false,
70
+ "vocab_size": 32000
71
+ }
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
+ }
sparsification_sftt.py ADDED
@@ -0,0 +1,1811 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import TrainerCallback, Trainer
2
+ from trl import SFTTrainer, DataCollatorForCompletionOnlyLM
3
+ from peft import PeftModel
4
+ from datasets import Dataset
5
+ from transformers.utils import is_sagemaker_mp_enabled, is_sagemaker_dp_enabled
6
+ from typing import Any, Dict, Union, Optional, Tuple
7
+ from torch.nn import MSELoss
8
+ from transformers.utils import is_flash_attn_2_available, logging
9
+ import inspect
10
+ import warnings
11
+ import math
12
+ import torch
13
+ import torch.nn as nn
14
+ import torch.nn.functional as F
15
+ import matplotlib.pyplot as plt
16
+ import numpy as np
17
+ import time
18
+ import os
19
+ import copy
20
+ import torchist
21
+
22
+ from transformers.models.mistral.modeling_mistral import (
23
+ MistralMLP,
24
+ MistralAttention,
25
+ MistralModel,
26
+ MistralDecoderLayer,
27
+ MistralConfig,
28
+ MISTRAL_ATTENTION_CLASSES,
29
+ MistralRMSNorm,
30
+ MistralForCausalLM,
31
+ MistralFlashAttention2,
32
+ )
33
+ from experiments.models.sparse_mistral.svd_router import (
34
+ low_rank_approximation,
35
+ SparsePredictor,
36
+ )
37
+ from utils.utils import (
38
+ print_size_of_model,
39
+ is_running_deepspeed,
40
+ is_mainprocess,
41
+ get_datetime,
42
+ ds_print,
43
+ )
44
+
45
+ if is_flash_attn_2_available():
46
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
47
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
48
+
49
+ _flash_supports_window_size = "window_size" in list(
50
+ inspect.signature(flash_attn_func).parameters
51
+ )
52
+ logger = logging.get_logger(__name__)
53
+
54
+
55
+ class SparseSFTTTrainer(SFTTrainer):
56
+ def __init__(self, *args, **kwargs):
57
+ self.regularization_coefficient = kwargs.pop("regularization_coefficient", 10)
58
+ self.use_sparse_regularization = kwargs.pop("use_sparse_regularization", False)
59
+ self.use_spm_loss = False
60
+ self.freeze_original_weights = False
61
+ self.regularization_type = kwargs.pop(
62
+ "regularization_type", "L1 positive activation"
63
+ )
64
+ assert self.regularization_type in [
65
+ "L2 activation",
66
+ "L1 positive activation",
67
+ ], f"Invalid regularization type: {self.regularization_type}"
68
+ self.sparse_layers = []
69
+ self.sparse_decoder_layers = []
70
+ super(SparseSFTTTrainer, self).__init__(*args, **kwargs)
71
+
72
+ def initialize_sparse_silu_layers(self, model):
73
+ self.sparse_layers = [
74
+ m for m in model.modules() if isinstance(m, MistralSparseSiluMLP)
75
+ ]
76
+
77
+ def initialize_sparse_decoder_layers(self, model):
78
+ self.sparse_decoder_layers = [
79
+ m for m in model.modules() if isinstance(m, SparseMistralDecoderLayer)
80
+ ]
81
+
82
+ def training_step(
83
+ self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]]
84
+ ) -> torch.Tensor:
85
+ """
86
+ Override the huggingface's training_step function to add a regularization term.
87
+ A regularization term is computed with intermediate values, which are freed after "backward()."
88
+ You need to set `retain_graph=True` inside `backward` function to keep the values.
89
+ """
90
+ model.train()
91
+ inputs = self._prepare_inputs(inputs)
92
+
93
+ with self.compute_loss_context_manager():
94
+ loss = self.compute_loss(model, inputs)
95
+
96
+ if self.args.n_gpu > 1:
97
+ loss = loss.mean() # mean() to average on multi-gpu parallel training
98
+ if not self.freeze_original_weights:
99
+ if loss is not None:
100
+ self.accelerator.backward(loss, retain_graph=False)
101
+
102
+ if self.use_sparse_regularization:
103
+ regularization_loss = self.compute_regularization(model)
104
+ if self.args.n_gpu > 1:
105
+ regularization_loss = regularization_loss.mean()
106
+ if regularization_loss is not None:
107
+ self.accelerator.backward(regularization_loss, retain_graph=True)
108
+ loss += regularization_loss
109
+
110
+ if self.use_spm_loss:
111
+ spm_loss = self.compute_spm_loss(model)
112
+ if self.args.n_gpu > 1:
113
+ spm_loss = spm_loss.mean()
114
+ if spm_loss is not None:
115
+ self.accelerator.backward(spm_loss, retain_graph=False)
116
+ loss += spm_loss
117
+
118
+ return loss.detach() / self.args.gradient_accumulation_steps
119
+
120
+ def compute_regularization(self, model):
121
+ """
122
+ Compute a sparse regularization loss for SiLU
123
+ """
124
+ loss = 0
125
+ if len(self.sparse_layers) == 0:
126
+ self.initialize_sparse_silu_layers(model)
127
+ num_layers = len(self.sparse_layers)
128
+
129
+ for module in self.sparse_layers:
130
+ if module.activation_norm is not None:
131
+ loss += module.activation_norm
132
+
133
+ loss /= num_layers
134
+ loss *= self.regularization_coefficient
135
+
136
+ if self.state.global_step % 20 == 0 and loss != 0:
137
+ print("Negative relularizer loss: ", loss.item())
138
+ return loss
139
+
140
+ def compute_spm_loss(self, model):
141
+ loss = 0
142
+ if len(self.sparse_decoder_layers) == 0:
143
+ self.initialize_sparse_decoder_layers(model)
144
+ for module in self.sparse_decoder_layers:
145
+ if module.distill_loss != None:
146
+ loss += module.distill_loss
147
+ if self.state.global_step % 20 == 0 and loss != 0:
148
+ print("Sparse Predictor Distillation loss: ", loss.item())
149
+ return loss
150
+
151
+ # def compute_loss(self, model, inputs, return_outputs=False):
152
+ # loss = super().compute_loss(model, inputs, return_outputs)
153
+ #
154
+ # if is_sagemaker_mp_enabled():
155
+ # import smdistributed.modelparallel.torch as smp
156
+ # @smp.step()
157
+ # def smp_forward_backward(model, inputs, gradient_accumulation_steps=1):
158
+ # outputs = model(**inputs)
159
+ # loss = outputs["loss"] if isinstance(outputs, dict) else outputs[0]
160
+ # loss /= gradient_accumulation_steps
161
+ # model.backward(loss)
162
+ # return loss
163
+ #
164
+ # loss_mb = smp_forward_backward(
165
+ # model, inputs, self.args.gradient_accumulation_steps
166
+ # )
167
+ # if self.use_sparse_regularization:
168
+ # return loss_mb.reduce_mean().detach().to(
169
+ # self.args.device
170
+ # ) + self.regularization_coefficient * self.compute_regularization(model)
171
+ # else:
172
+ # return loss_mb.reduce_mean().detach().to(self)
173
+ #
174
+ # if return_outputs:
175
+ # classification_loss, outputs = loss
176
+ # else:
177
+ # classification_loss = loss
178
+ #
179
+ # loss = classification_loss
180
+ # if self.use_sparse_regularization:
181
+ # regularization_loss = self.compute_regularization(model)
182
+ # loss += self.regularization_coefficient * regularization_loss
183
+ #
184
+ # return (loss, outputs) if return_outputs else loss
185
+
186
+
187
+ class SparseTrainer(Trainer):
188
+ def __init__(self, *args, **kwargs):
189
+ self.regularization_coefficient = kwargs.pop("regularization_coefficient", 10)
190
+ self.use_sparse_regularization = kwargs.pop("use_sparse_regularization", False)
191
+ self.use_spm_loss = False
192
+ self.freeze_original_weights = False
193
+ self.regularization_type = kwargs.pop(
194
+ "regularization_type", "L1 positive activation"
195
+ )
196
+ assert self.regularization_type in [
197
+ "L2 activation",
198
+ "L1 positive activation",
199
+ ], f"Invalid regularization type: {self.regularization_type}"
200
+ self.sparse_layers = []
201
+ self.sparse_decoder_layers = []
202
+ super(SparseTrainer, self).__init__(*args, **kwargs)
203
+
204
+ def initialize_sparse_silu_layers(self, model):
205
+ self.sparse_layers = [
206
+ m for m in model.modules() if isinstance(m, MistralSparseSiluMLP)
207
+ ]
208
+
209
+ def initialize_sparse_decoder_layers(self, model):
210
+ self.sparse_decoder_layers = [
211
+ m for m in model.modules() if isinstance(m, SparseMistralDecoderLayer)
212
+ ]
213
+
214
+ def training_step(
215
+ self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]]
216
+ ) -> torch.Tensor:
217
+ """
218
+ Override the huggingface's training_step function to add a regularization term.
219
+ A regularization term is computed with intermediate values, which are freed after "backward()."
220
+ You need to set `retain_graph=True` inside `backward` function to keep the values.
221
+ """
222
+ model.train()
223
+ inputs = self._prepare_inputs(inputs)
224
+
225
+ with self.compute_loss_context_manager():
226
+ loss = self.compute_loss(model, inputs)
227
+
228
+ if self.args.n_gpu > 1:
229
+ loss = loss.mean() # mean() to average on multi-gpu parallel training
230
+ if not self.freeze_original_weights:
231
+ if loss is not None:
232
+ self.accelerator.backward(loss, retain_graph=False)
233
+
234
+ if self.use_sparse_regularization:
235
+ regularization_loss = self.compute_regularization(model)
236
+ if self.args.n_gpu > 1:
237
+ regularization_loss = regularization_loss.mean()
238
+ if regularization_loss is not None:
239
+ self.accelerator.backward(regularization_loss, retain_graph=True)
240
+ loss += regularization_loss
241
+
242
+ if self.use_spm_loss:
243
+ spm_loss = self.compute_spm_loss(model)
244
+ if self.args.n_gpu > 1:
245
+ spm_loss = spm_loss.mean()
246
+ if spm_loss is not None:
247
+ self.accelerator.backward(spm_loss, retain_graph=False)
248
+ loss += spm_loss
249
+
250
+ return loss.detach() / self.args.gradient_accumulation_steps
251
+
252
+ def compute_regularization(self, model):
253
+ """
254
+ Compute a sparse regularization loss for SiLU
255
+ """
256
+ loss = 0
257
+ if len(self.sparse_layers) == 0:
258
+ self.initialize_sparse_silu_layers(model)
259
+ num_layers = len(self.sparse_layers)
260
+
261
+ for module in self.sparse_layers:
262
+ if module.activation_norm is not None:
263
+ loss += module.activation_norm
264
+
265
+ loss /= num_layers
266
+ loss *= self.regularization_coefficient
267
+
268
+ if self.state.global_step % 20 == 0 and loss != 0:
269
+ print("Negative relularizer loss: ", loss.item())
270
+ return loss
271
+
272
+ def compute_spm_loss(self, model):
273
+ loss = 0
274
+ if len(self.sparse_decoder_layers) == 0:
275
+ self.initialize_sparse_decoder_layers(model)
276
+ for module in self.sparse_decoder_layers:
277
+ if module.distill_loss != None:
278
+ loss += module.distill_loss
279
+ if self.state.global_step % 20 == 0 and loss != 0:
280
+ print("Sparse Predictor Distillation loss: ", loss.item())
281
+ return loss
282
+
283
+
284
+ class SparseSiLU(nn.SiLU):
285
+ def __init__(self, threshold):
286
+ super(SparseSiLU, self).__init__()
287
+ self.threshold = threshold
288
+ self.m = nn.Threshold(self.threshold, 0)
289
+
290
+ def set_new_threshold(self, threshold):
291
+ self.threshold = threshold
292
+ self.m = nn.Threshold(threshold, 0)
293
+
294
+ def forward(self, x):
295
+ act = super(SparseSiLU, self).forward(x)
296
+ return self.m(act) - self.m(-act)
297
+
298
+
299
+ def rotate_half(x):
300
+ """Rotates half the hidden dims of the input."""
301
+ x1 = x[..., : x.shape[-1] // 2]
302
+ x2 = x[..., x.shape[-1] // 2 :]
303
+ return torch.cat((-x2, x1), dim=-1)
304
+
305
+
306
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
307
+ """Applies Rotary Position Embedding to the query and key tensors.
308
+
309
+ Args:
310
+ q (`torch.Tensor`): The query tensor.
311
+ k (`torch.Tensor`): The key tensor.
312
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
313
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
314
+ position_ids (`torch.Tensor`):
315
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
316
+ used to pass offsetted position ids when working with a KV-cache.
317
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
318
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
319
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
320
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
321
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
322
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
323
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
324
+ Returns:
325
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
326
+ """
327
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
328
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
329
+ q_embed = (q * cos) + (rotate_half(q) * sin)
330
+ k_embed = (k * cos) + (rotate_half(k) * sin)
331
+ return q_embed, k_embed
332
+
333
+
334
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
335
+ """
336
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
337
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
338
+ """
339
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
340
+ if n_rep == 1:
341
+ return hidden_states
342
+ hidden_states = hidden_states[:, :, None, :, :].expand(
343
+ batch, num_key_value_heads, n_rep, slen, head_dim
344
+ )
345
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
346
+
347
+
348
+ def _get_unpad_data(attention_mask):
349
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
350
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
351
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
352
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
353
+ return (
354
+ indices,
355
+ cu_seqlens,
356
+ max_seqlen_in_batch,
357
+ )
358
+
359
+
360
+ class SparseMistralFlashAttention(MistralFlashAttention2):
361
+ """
362
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
363
+ and "Generating Long Sequences with Sparse Transformers".
364
+ """
365
+
366
+ def __init__(self, *args, **kwargs):
367
+ super().__init__(*args, **kwargs)
368
+ self.counts = 0
369
+ self.pre_attn_sparsity = 0
370
+ self.visit_counts = 0
371
+ self.is_stats = False
372
+ self.pre_attn_std = 0
373
+ self.pre_attn_threshold = 0
374
+
375
+ # Activation Histograms
376
+ self.is_collect_histogram = False
377
+ num_bins = 20000
378
+ self.num_bins = num_bins
379
+ self.hist_min = -2
380
+ self.hist_max = 2
381
+ self.histogram_bins = torch.linspace(
382
+ self.hist_min, self.hist_max, num_bins - 2
383
+ )
384
+ self.histogram_bins = torch.cat(
385
+ [torch.tensor([-torch.inf]), self.histogram_bins, torch.tensor([torch.inf])]
386
+ )
387
+ self.pre_mlp_std = 0
388
+ self.pre_mlp_hist_counts = torch.zeros(num_bins - 1)
389
+ self.pre_act_hist_counts = torch.zeros(num_bins - 1)
390
+ self.post_act_hist_counts = torch.zeros(num_bins - 1)
391
+
392
+ def activate_stats(self):
393
+ self.is_stats = True
394
+ self.visit_counts = 0
395
+ # self.pre_attn_sparsity = 0
396
+ self.pre_attn_std = 0
397
+
398
+ def deactivate_stats(self):
399
+ self.is_stats = False
400
+
401
+ def forward(
402
+ self,
403
+ hidden_states: torch.Tensor,
404
+ attention_mask: Optional[torch.Tensor] = None,
405
+ position_ids: Optional[torch.LongTensor] = None,
406
+ past_key_value: Optional = None,
407
+ output_attentions: bool = False,
408
+ use_cache: bool = False,
409
+ **kwargs,
410
+ ):
411
+ if "padding_mask" in kwargs:
412
+ warnings.warn(
413
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
414
+ )
415
+
416
+ # overwrite attention_mask with padding_mask
417
+ attention_mask = kwargs.pop("padding_mask")
418
+ bsz, q_len, _ = hidden_states.size()
419
+ mask = abs(hidden_states - hidden_states.mean()) < self.pre_attn_threshold
420
+ hidden_states[mask] = 0
421
+ self.counts += 1
422
+
423
+ if self.is_stats:
424
+ self.pre_attn_sparsity = (
425
+ self.pre_attn_sparsity * self.visit_counts
426
+ + (hidden_states == 0).float().mean()
427
+ ) / (self.visit_counts + 1)
428
+ self.pre_attn_std = (
429
+ self.pre_attn_std * self.visit_counts + 0.5 * hidden_states.std()
430
+ ) / (self.visit_counts + 1)
431
+ self.visit_counts += 1
432
+ self.counts -= 1
433
+
434
+ if self.counts == 10:
435
+ print(f"Attention {self.layer_idx}: ", (hidden_states == 0).float().mean())
436
+ print(
437
+ mask.shape,
438
+ )
439
+
440
+ query_states = self.q_proj(hidden_states)
441
+ key_states = self.k_proj(hidden_states)
442
+ value_states = self.v_proj(hidden_states)
443
+
444
+ query_states = query_states.view(
445
+ bsz, q_len, self.num_heads, self.head_dim
446
+ ).transpose(1, 2)
447
+ key_states = key_states.view(
448
+ bsz, q_len, self.num_key_value_heads, self.head_dim
449
+ ).transpose(1, 2)
450
+ value_states = value_states.view(
451
+ bsz, q_len, self.num_key_value_heads, self.head_dim
452
+ ).transpose(1, 2)
453
+
454
+ kv_seq_len = key_states.shape[-2]
455
+ if past_key_value is not None:
456
+ if self.layer_idx is None:
457
+ raise ValueError(
458
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
459
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
460
+ "with a layer index."
461
+ )
462
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
463
+
464
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
465
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
466
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
467
+
468
+ query_states, key_states = apply_rotary_pos_emb(
469
+ query_states, key_states, cos, sin, position_ids
470
+ )
471
+
472
+ use_sliding_windows = (
473
+ _flash_supports_window_size
474
+ and getattr(self.config, "sliding_window", None) is not None
475
+ and kv_seq_len > self.config.sliding_window
476
+ )
477
+
478
+ if not _flash_supports_window_size:
479
+ logger.warning_once(
480
+ "The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
481
+ " make sure to upgrade flash-attn library."
482
+ )
483
+
484
+ if past_key_value is not None:
485
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
486
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
487
+ if (
488
+ getattr(self.config, "sliding_window", None) is not None
489
+ and kv_seq_len > self.config.sliding_window
490
+ and cache_has_contents
491
+ ):
492
+ slicing_tokens = 1 - self.config.sliding_window
493
+
494
+ past_key = past_key_value[self.layer_idx][0]
495
+ past_value = past_key_value[self.layer_idx][1]
496
+
497
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
498
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
499
+
500
+ if past_key.shape[-2] != self.config.sliding_window - 1:
501
+ raise ValueError(
502
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
503
+ f" {past_key.shape}"
504
+ )
505
+
506
+ if attention_mask is not None:
507
+ attention_mask = attention_mask[:, slicing_tokens:]
508
+ attention_mask = torch.cat(
509
+ [attention_mask, torch.ones_like(attention_mask[:, -1:])],
510
+ dim=-1,
511
+ )
512
+
513
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
514
+ key_states, value_states = past_key_value.update(
515
+ key_states, value_states, self.layer_idx, cache_kwargs
516
+ )
517
+
518
+ # repeat k/v heads if n_kv_heads < n_heads
519
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
520
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
521
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
522
+
523
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
524
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
525
+ # cast them back in float16 just to be sure everything works as expected.
526
+ input_dtype = query_states.dtype
527
+ if input_dtype == torch.float32:
528
+ if torch.is_autocast_enabled():
529
+ target_dtype = torch.get_autocast_gpu_dtype()
530
+ # Handle the case where the model is quantized
531
+ elif hasattr(self.config, "_pre_quantization_dtype"):
532
+ target_dtype = self.config._pre_quantization_dtype
533
+ else:
534
+ target_dtype = self.q_proj.weight.dtype
535
+
536
+ logger.warning_once(
537
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
538
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
539
+ f" {target_dtype}."
540
+ )
541
+
542
+ query_states = query_states.to(target_dtype)
543
+ key_states = key_states.to(target_dtype)
544
+ value_states = value_states.to(target_dtype)
545
+
546
+ # Reashape to the expected shape for Flash Attention
547
+ query_states = query_states.transpose(1, 2)
548
+ key_states = key_states.transpose(1, 2)
549
+ value_states = value_states.transpose(1, 2)
550
+
551
+ attn_output = self._flash_attention_forward(
552
+ query_states,
553
+ key_states,
554
+ value_states,
555
+ attention_mask,
556
+ q_len,
557
+ dropout=dropout_rate,
558
+ use_sliding_windows=use_sliding_windows,
559
+ )
560
+
561
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
562
+ attn_output = self.o_proj(attn_output)
563
+
564
+ if not output_attentions:
565
+ attn_weights = None
566
+
567
+ return attn_output, attn_weights, past_key_value
568
+
569
+ def _flash_attention_forward(
570
+ self,
571
+ query_states,
572
+ key_states,
573
+ value_states,
574
+ attention_mask,
575
+ query_length,
576
+ dropout=0.0,
577
+ softmax_scale=None,
578
+ use_sliding_windows=False,
579
+ ):
580
+ """
581
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
582
+ first unpad the input, then computes the attention scores and pad the final attention scores.
583
+
584
+ Args:
585
+ query_states (`torch.Tensor`):
586
+ Input query states to be passed to Flash Attention API
587
+ key_states (`torch.Tensor`):
588
+ Input key states to be passed to Flash Attention API
589
+ value_states (`torch.Tensor`):
590
+ Input value states to be passed to Flash Attention API
591
+ attention_mask (`torch.Tensor`):
592
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
593
+ position of padding tokens and 1 for the position of non-padding tokens.
594
+ dropout (`float`):
595
+ Attention dropout
596
+ softmax_scale (`float`, *optional*):
597
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
598
+ use_sliding_windows (`bool`, *optional*):
599
+ Whether to activate sliding window attention.
600
+ """
601
+ if not self._flash_attn_uses_top_left_mask:
602
+ causal = self.is_causal
603
+ else:
604
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
605
+ causal = self.is_causal and query_length != 1
606
+
607
+ # Contains at least one padding token in the sequence
608
+ if attention_mask is not None:
609
+ batch_size = query_states.shape[0]
610
+ (
611
+ query_states,
612
+ key_states,
613
+ value_states,
614
+ indices_q,
615
+ cu_seq_lens,
616
+ max_seq_lens,
617
+ ) = self._upad_input(
618
+ query_states, key_states, value_states, attention_mask, query_length
619
+ )
620
+
621
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
622
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
623
+
624
+ if not use_sliding_windows:
625
+ attn_output_unpad = flash_attn_varlen_func(
626
+ query_states,
627
+ key_states,
628
+ value_states,
629
+ cu_seqlens_q=cu_seqlens_q,
630
+ cu_seqlens_k=cu_seqlens_k,
631
+ max_seqlen_q=max_seqlen_in_batch_q,
632
+ max_seqlen_k=max_seqlen_in_batch_k,
633
+ dropout_p=dropout,
634
+ softmax_scale=softmax_scale,
635
+ causal=causal,
636
+ )
637
+ else:
638
+ attn_output_unpad = flash_attn_varlen_func(
639
+ query_states,
640
+ key_states,
641
+ value_states,
642
+ cu_seqlens_q=cu_seqlens_q,
643
+ cu_seqlens_k=cu_seqlens_k,
644
+ max_seqlen_q=max_seqlen_in_batch_q,
645
+ max_seqlen_k=max_seqlen_in_batch_k,
646
+ dropout_p=dropout,
647
+ softmax_scale=softmax_scale,
648
+ causal=causal,
649
+ window_size=(
650
+ self.config.sliding_window,
651
+ self.config.sliding_window,
652
+ ),
653
+ )
654
+
655
+ attn_output = pad_input(
656
+ attn_output_unpad, indices_q, batch_size, query_length
657
+ )
658
+ else:
659
+ if not use_sliding_windows:
660
+ attn_output = flash_attn_func(
661
+ query_states,
662
+ key_states,
663
+ value_states,
664
+ dropout,
665
+ softmax_scale=softmax_scale,
666
+ causal=causal,
667
+ )
668
+ else:
669
+ attn_output = flash_attn_func(
670
+ query_states,
671
+ key_states,
672
+ value_states,
673
+ dropout,
674
+ softmax_scale=softmax_scale,
675
+ causal=causal,
676
+ window_size=(
677
+ self.config.sliding_window,
678
+ self.config.sliding_window,
679
+ ),
680
+ )
681
+
682
+ return attn_output
683
+
684
+ def _upad_input(
685
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
686
+ ):
687
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
688
+
689
+ # On the first iteration we need to properly re-create the padding mask
690
+ # by slicing it on the proper place
691
+ if kv_seq_len != attention_mask.shape[-1]:
692
+ attention_mask_num_tokens = attention_mask.shape[-1]
693
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
694
+
695
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
696
+
697
+ key_layer = index_first_axis(
698
+ key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
699
+ )
700
+ value_layer = index_first_axis(
701
+ value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
702
+ )
703
+
704
+ if query_length == kv_seq_len:
705
+ query_layer = index_first_axis(
706
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim),
707
+ indices_k,
708
+ )
709
+ cu_seqlens_q = cu_seqlens_k
710
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
711
+ indices_q = indices_k
712
+ elif query_length == 1:
713
+ max_seqlen_in_batch_q = 1
714
+ cu_seqlens_q = torch.arange(
715
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
716
+ ) # There is a memcpy here, that is very bad.
717
+ indices_q = cu_seqlens_q[:-1]
718
+ query_layer = query_layer.squeeze(1)
719
+ else:
720
+ # The -q_len: slice assumes left padding.
721
+ attention_mask = attention_mask[:, -query_length:]
722
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
723
+ query_layer, attention_mask
724
+ )
725
+
726
+ return (
727
+ query_layer,
728
+ key_layer,
729
+ value_layer,
730
+ indices_q,
731
+ (cu_seqlens_q, cu_seqlens_k),
732
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
733
+ )
734
+
735
+
736
+ class SparseMistralAttention(MistralAttention):
737
+ def __init__(self, *args, **kwargs):
738
+ super().__init__(*args, **kwargs)
739
+ self.counts = 0
740
+ self.pre_attn_sparsity = 0
741
+ self.visit_counts = 0
742
+ self.is_stats = False
743
+ self.pre_attn_std = 0
744
+ self.pre_attn_threshold = 0
745
+
746
+ # Activation Histograms
747
+ self.is_collect_histogram = False
748
+ num_bins = 20000
749
+ self.num_bins = num_bins
750
+ self.hist_min = -2
751
+ self.hist_max = 2
752
+ self.histogram_bins = torch.linspace(
753
+ self.hist_min, self.hist_max, num_bins - 2
754
+ )
755
+ self.histogram_bins = torch.cat(
756
+ [torch.tensor([-torch.inf]), self.histogram_bins, torch.tensor([torch.inf])]
757
+ )
758
+ self.pre_mlp_std = 0
759
+ self.pre_attn_hist_counts = torch.zeros(num_bins - 1)
760
+ self.post_qk_hist_counts = torch.zeros(num_bins - 1)
761
+
762
+ def activate_stats(self):
763
+ self.is_stats = True
764
+ self.visit_counts = 0
765
+ self.pre_attn_sparsity = 0
766
+ self.pre_attn_std = 0
767
+
768
+ def deactivate_stats(self):
769
+ self.is_stats = False
770
+
771
+ def forward(
772
+ self,
773
+ hidden_states: torch.Tensor,
774
+ attention_mask: Optional[torch.Tensor] = None,
775
+ position_ids: Optional[torch.LongTensor] = None,
776
+ past_key_value: Optional = None,
777
+ output_attentions: bool = False,
778
+ use_cache: bool = False,
779
+ **kwargs,
780
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
781
+ if "padding_mask" in kwargs:
782
+ warnings.warn(
783
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
784
+ )
785
+ bsz, q_len, _ = hidden_states.size()
786
+ mask = abs(hidden_states - hidden_states.mean()) < self.pre_attn_threshold
787
+ hidden_states[mask] = 0
788
+
789
+ if self.is_stats:
790
+ self.pre_attn_hist_counts += torch.cat(
791
+ (
792
+ (hidden_states < self.hist_min).sum().unsqueeze(0),
793
+ torch.histc(
794
+ hidden_states.float(),
795
+ bins=self.num_bins - 3,
796
+ min=self.hist_min,
797
+ max=self.hist_max,
798
+ ),
799
+ (hidden_states > self.hist_max).sum().unsqueeze(0),
800
+ )
801
+ ).cpu()
802
+
803
+ self.counts += 1
804
+ if self.counts == 10:
805
+ print(
806
+ f"Attention {self.layer_idx}: {float((hidden_states == 0).float().mean()) * 100 : .3f}"
807
+ )
808
+ self.counts += 1
809
+
810
+ query_states = self.q_proj(hidden_states)
811
+ key_states = self.k_proj(hidden_states)
812
+ value_states = self.v_proj(hidden_states)
813
+
814
+ query_states = query_states.view(
815
+ bsz, q_len, self.num_heads, self.head_dim
816
+ ).transpose(1, 2)
817
+ key_states = key_states.view(
818
+ bsz, q_len, self.num_key_value_heads, self.head_dim
819
+ ).transpose(1, 2)
820
+ value_states = value_states.view(
821
+ bsz, q_len, self.num_key_value_heads, self.head_dim
822
+ ).transpose(1, 2)
823
+
824
+ kv_seq_len = key_states.shape[-2]
825
+ if past_key_value is not None:
826
+ if self.layer_idx is None:
827
+ raise ValueError(
828
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
829
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
830
+ "with a layer index."
831
+ )
832
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
833
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
834
+ query_states, key_states = apply_rotary_pos_emb(
835
+ query_states, key_states, cos, sin, position_ids
836
+ )
837
+
838
+ if past_key_value is not None:
839
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
840
+ key_states, value_states = past_key_value.update(
841
+ key_states, value_states, self.layer_idx, cache_kwargs
842
+ )
843
+
844
+ # repeat k/v heads if n_kv_heads < n_heads
845
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
846
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
847
+
848
+ attn_weights = torch.matmul(
849
+ query_states, key_states.transpose(2, 3)
850
+ ) / math.sqrt(self.head_dim)
851
+
852
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
853
+ raise ValueError(
854
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
855
+ f" {attn_weights.size()}"
856
+ )
857
+
858
+ if attention_mask is not None:
859
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
860
+ raise ValueError(
861
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
862
+ )
863
+
864
+ attn_weights = attn_weights + attention_mask
865
+
866
+ # upcast attention to fp32
867
+ attn_weights = nn.functional.softmax(
868
+ attn_weights, dim=-1, dtype=torch.float32
869
+ ).to(query_states.dtype)
870
+ attn_weights = nn.functional.dropout(
871
+ attn_weights, p=self.attention_dropout, training=self.training
872
+ )
873
+ if self.is_stats:
874
+ self.post_qk_hist_counts += torch.cat(
875
+ (
876
+ (attn_weights < self.hist_min).sum().unsqueeze(0),
877
+ torch.histc(
878
+ attn_weights.float(),
879
+ bins=self.num_bins - 3,
880
+ min=self.hist_min,
881
+ max=self.hist_max,
882
+ ),
883
+ (attn_weights > self.hist_max).sum().unsqueeze(0),
884
+ )
885
+ ).cpu()
886
+ attn_output = torch.matmul(attn_weights, value_states)
887
+
888
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
889
+ raise ValueError(
890
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
891
+ f" {attn_output.size()}"
892
+ )
893
+
894
+ attn_output = attn_output.transpose(1, 2).contiguous()
895
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
896
+
897
+ attn_output = self.o_proj(attn_output)
898
+
899
+ if not output_attentions:
900
+ attn_weights = None
901
+
902
+ return attn_output, attn_weights, past_key_value
903
+
904
+
905
+ class MistralSparseSiluMLP(MistralMLP):
906
+ def __init__(self, config, *args, **kwargs):
907
+ super().__init__(config)
908
+ self.swish_outputs = None
909
+ self.relu = nn.ReLU()
910
+ self.resilu = nn.Sequential(nn.SiLU())
911
+
912
+ self.kill_sparse_swish_outputs = False
913
+ self.cut_pre_mlp = False
914
+ self.dead_percentage = 0
915
+ self.pre_mlp_sparsity = 0
916
+ self.is_stats = False
917
+ self.visit_counts = 0
918
+
919
+ # Hyperparameters to tune
920
+ self.dead_threshold = kwargs.pop("dead_threshold", 0)
921
+ self.pre_mlp_threshold = kwargs.pop("pre_mlp_threshold", 0)
922
+ self.pre_mlp_dead_threshold = kwargs.pop("pre_mlp_dead_threshold", 0)
923
+ self.use_sparse_regularization = kwargs.pop("use_sparse_regularization", True)
924
+ self.regularization_type = kwargs.pop(
925
+ "regularization_type", "L1 regularization"
926
+ )
927
+ self.regularization_threshold = kwargs.pop("regularization_threshold", 0.5)
928
+ self.use_relu = kwargs.pop("use_relu", False)
929
+ self.use_resilu = kwargs.pop("use_resilu", False)
930
+ self.activation_norm = None
931
+
932
+ # Activation Histograms
933
+ self.is_collect_histogram = False
934
+ num_bins = 20000
935
+ self.num_bins = num_bins
936
+ self.hist_min = -2
937
+ self.hist_max = 2
938
+ self.histogram_bins = torch.linspace(
939
+ self.hist_min, self.hist_max, num_bins - 2
940
+ )
941
+ self.histogram_bins = torch.cat(
942
+ [torch.tensor([-torch.inf]), self.histogram_bins, torch.tensor([torch.inf])]
943
+ )
944
+ self.pre_mlp_std = 0
945
+ self.pre_mlp_hist_counts = torch.zeros(num_bins - 1).to(
946
+ self.gate_proj.weight.device
947
+ )
948
+ self.pre_act_hist_counts = torch.zeros(num_bins - 1).to(
949
+ self.gate_proj.weight.device
950
+ )
951
+ self.post_act_hist_counts = torch.zeros(num_bins - 1).to(
952
+ self.gate_proj.weight.device
953
+ )
954
+ self.t = 0
955
+ self.count = 0
956
+ self.agg_sparsity = 0
957
+
958
+ # Sparse activation function
959
+ self.sparse_act_fn = SparseSiLU(threshold=self.dead_threshold)
960
+
961
+ def activate_stats(self, is_collect_histogram: bool = True):
962
+ self.is_stats = True
963
+ self.dead_percentage = 0
964
+ self.visit_counts = 0
965
+ self.is_collect_histogram = is_collect_histogram
966
+ self.histogram_counts = torch.zeros(2000) # .to(self.down_proj.weight.device)
967
+
968
+ def deactivate_stats(self):
969
+ self.is_stats = False
970
+
971
+ def collect_stats(
972
+ self,
973
+ pre_mlp,
974
+ pre_activation,
975
+ post_activation,
976
+ ):
977
+ start_time = time.time()
978
+ pre_mlp = pre_mlp.float()
979
+ pre_activation = pre_activation.float()
980
+ post_activation = torch.abs(post_activation.float())
981
+ # self.histogram_bins=self.histogram_bins.to(pre_activation.device).type(pre_activation.dtype)
982
+ # self.pre_mlp_hist_counts = torch.histogram(pre_mlp, bins=self.histogram_bins)[0]
983
+ if torch.cuda.is_available():
984
+ self.pre_mlp_hist_counts += torch.cat(
985
+ (
986
+ (pre_mlp < self.hist_min).sum().unsqueeze(0),
987
+ torch.histc(
988
+ pre_mlp,
989
+ bins=self.num_bins - 3,
990
+ min=self.hist_min,
991
+ max=self.hist_max,
992
+ ),
993
+ (pre_mlp > self.hist_max).sum().unsqueeze(0),
994
+ )
995
+ ).cpu()
996
+ self.pre_act_hist_counts += torch.cat(
997
+ (
998
+ (pre_activation < self.hist_min).sum().unsqueeze(0),
999
+ torch.histc(
1000
+ pre_activation,
1001
+ bins=self.num_bins - 3,
1002
+ min=self.hist_min,
1003
+ max=self.hist_max,
1004
+ ),
1005
+ (pre_activation > self.hist_max).sum().unsqueeze(0),
1006
+ )
1007
+ ).cpu()
1008
+ if torch.cuda.is_available():
1009
+ self.post_act_hist_counts += torch.cat(
1010
+ (
1011
+ (post_activation < self.hist_min).sum().unsqueeze(0),
1012
+ torch.histc(
1013
+ post_activation,
1014
+ bins=self.num_bins - 3,
1015
+ min=self.hist_min,
1016
+ max=self.hist_max,
1017
+ ),
1018
+ (pre_activation > self.hist_max).sum().unsqueeze(0),
1019
+ )
1020
+ ).cpu()
1021
+ else:
1022
+ self.pre_mlp_hist_counts = torch.histogram(
1023
+ pre_mlp, bins=self.histogram_bins
1024
+ )[0]
1025
+ self.pre_act_hist_counts += torch.histogram(
1026
+ pre_activation, bins=self.histogram_bins
1027
+ )[0]
1028
+ self.post_act_hist_counts += torch.histogram(
1029
+ post_activation, bins=self.histogram_bins
1030
+ )[0]
1031
+
1032
+ self.t += time.time() - start_time
1033
+ if self.visit_counts % 30 == 0:
1034
+ print(f"Time taken to collect stats: {self.t}s.")
1035
+
1036
+ def forward(
1037
+ self,
1038
+ x,
1039
+ sp_mask: torch.tensor = None,
1040
+ ):
1041
+ """
1042
+ If kill_sparse_swish_outputs is set to False, this layer functions exactly like a normal MLP layer.
1043
+ """
1044
+ if sp_mask != None: # When sparse mask is given
1045
+ return self.down_proj(
1046
+ self.sparse_act_fn(self.gate_proj(x) * sp_mask) * self.up_proj(x)
1047
+ ) # Todo: This doesn't accelerate runtime (instead slowing down)
1048
+
1049
+ elif self.use_relu or self.use_resilu:
1050
+ if self.use_relu:
1051
+ post_act = self.relu(self.gate_proj(x))
1052
+ else:
1053
+ post_act = self.resilu(self.gate_proj(x))
1054
+ self.count += 1
1055
+ if self.count <= 1:
1056
+ print("USING RELU or ReSiLU!!!!")
1057
+
1058
+ if self.is_stats:
1059
+ dead_neurons = post_act == 0
1060
+ dead_percentage = dead_neurons.float().mean()
1061
+ agg_sparsity = dead_neurons.all(dim=0).float().mean()
1062
+
1063
+ self.dead_percentage = (
1064
+ self.dead_percentage * self.visit_counts + dead_percentage
1065
+ ) / (self.visit_counts + 1)
1066
+ self.agg_sparsity = (
1067
+ self.agg_sparsity * self.visit_counts + agg_sparsity
1068
+ ) / (self.visit_counts + 1)
1069
+ self.visit_counts += 1
1070
+
1071
+ return self.down_proj(post_act * self.up_proj(x))
1072
+
1073
+ else:
1074
+ self.count += 1
1075
+
1076
+ if self.cut_pre_mlp:
1077
+ if (
1078
+ self.is_stats
1079
+ ): # collect statistics for deciding threhold value to cut values of hidden vec before mlp
1080
+ self.pre_mlp_std = (
1081
+ x.std() * 0.6 + self.visit_counts * self.pre_mlp_std
1082
+ ) / (self.visit_counts + 1)
1083
+ self.count -= 1
1084
+ x[abs(x) < self.pre_mlp_threshold] = 0
1085
+
1086
+ pre_act = self.gate_proj(x)
1087
+ post_act = self.act_fn(pre_act)
1088
+ if self.kill_sparse_swish_outputs:
1089
+ dead_neurons = post_act.abs() <= self.dead_threshold
1090
+ # print("pre act sparsity: ", (pre_act==0).float().mean())
1091
+
1092
+ dead_percentage = dead_neurons.float().mean()
1093
+ agg_sparsity = dead_neurons.all(dim=0).float().mean()
1094
+
1095
+ if self.is_stats:
1096
+ self.dead_percentage = (
1097
+ self.dead_percentage * self.visit_counts + dead_percentage
1098
+ ) / (self.visit_counts + 1)
1099
+ self.agg_sparsity = (
1100
+ self.agg_sparsity * self.visit_counts + agg_sparsity
1101
+ ) / (self.visit_counts + 1)
1102
+ self.pre_mlp_sparsity = (
1103
+ self.pre_mlp_sparsity * self.visit_counts
1104
+ + (x == 0).float().mean()
1105
+ ) / (self.visit_counts + 1)
1106
+
1107
+ self.visit_counts += 1
1108
+
1109
+ self.a = dead_percentage
1110
+
1111
+ # print(self.agg_sparsity)
1112
+
1113
+ # Collect histogram stats
1114
+ if (
1115
+ self.is_collect_histogram
1116
+ and pre_act.eq(0).float().mean() < 0.99
1117
+ ): # Padded dataset
1118
+ self.collect_stats(x, pre_act, post_act)
1119
+
1120
+ post_act[dead_neurons] = 0
1121
+ if self.count == 10:
1122
+ print(
1123
+ f"sparsity: {dead_percentage}/ pre-activation sparsity: {(x==0).float().mean()}"
1124
+ )
1125
+
1126
+ out = self.down_proj(post_act * self.up_proj(x))
1127
+ if self.use_sparse_regularization:
1128
+ if self.regularization_type == "L1 regularization":
1129
+ self.activation_norm = torch.abs(post_act)[
1130
+ post_act < self.regularization_threshold
1131
+ ].mean()
1132
+ elif self.regularization_type == "L2 regularization":
1133
+ self.activation_norm = torch.sqrt(
1134
+ torch.square(post_act)[post_act < self.regularization_threshold]
1135
+ ).mean()
1136
+
1137
+ return out
1138
+
1139
+
1140
+ class SparseMistralDecoderLayer(MistralDecoderLayer):
1141
+ def __init__(
1142
+ self,
1143
+ config: MistralConfig,
1144
+ layer_idx: int,
1145
+ decoder_layer: MistralDecoderLayer,
1146
+ init_svd: bool = True,
1147
+ *args,
1148
+ **kwargs,
1149
+ ):
1150
+ assert isinstance(
1151
+ decoder_layer.mlp, MistralSparseSiluMLP
1152
+ ), f"{type(decoder_layer.mlp)} should MistralSparseSiluMLP."
1153
+
1154
+ super().__init__(config, layer_idx)
1155
+ self.hidden_size = config.hidden_size
1156
+ self.intermediate_size = config.intermediate_size
1157
+
1158
+ self.init_svd = init_svd
1159
+ self.self_attn = decoder_layer.self_attn
1160
+
1161
+ self.mlp = decoder_layer.mlp
1162
+ self.input_layernorm = decoder_layer.input_layernorm
1163
+ self.post_attention_layernorm = decoder_layer.post_attention_layernorm
1164
+
1165
+ # Sparse predictor for mlp (initialized with SVD decomposed matrix)
1166
+ self.low_rank = kwargs.pop("low_rank", 64)
1167
+ self.sparse_act_func = decoder_layer.mlp.sparse_act_fn
1168
+
1169
+ print(
1170
+ f"Setting {layer_idx}th mlp layer's sparse predictor... svd init: {init_svd}"
1171
+ )
1172
+ self.sp_mlp = low_rank_approximation(
1173
+ decoder_layer.mlp.gate_proj,
1174
+ act_func=self.sparse_act_func,
1175
+ init_svd=init_svd,
1176
+ )
1177
+ self.use_async = kwargs.pop("use_async", False)
1178
+ self.use_sparse_predictor = False
1179
+ self.distill_loss = None
1180
+
1181
+ def forward(
1182
+ self,
1183
+ hidden_states: torch.Tensor,
1184
+ attention_mask: Optional[torch.Tensor] = None,
1185
+ position_ids: Optional[torch.LongTensor] = None,
1186
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1187
+ output_attentions: Optional[bool] = False,
1188
+ use_cache: Optional[bool] = False,
1189
+ **kwargs,
1190
+ ) -> Tuple[
1191
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
1192
+ ]:
1193
+ print("hidden_states shape: ", hidden_states.shape)
1194
+ if "padding_mask" in kwargs:
1195
+ warnings.warn(
1196
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1197
+ )
1198
+
1199
+ residual = hidden_states
1200
+ sp_mask = None
1201
+
1202
+ if self.use_async:
1203
+ sp_mask = self.sp_mlp(hidden_states)
1204
+
1205
+ hidden_states = self.input_layernorm(hidden_states)
1206
+
1207
+ # Self Attention
1208
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1209
+ hidden_states=hidden_states,
1210
+ attention_mask=attention_mask,
1211
+ position_ids=position_ids,
1212
+ past_key_value=past_key_value,
1213
+ output_attentions=output_attentions,
1214
+ use_cache=use_cache,
1215
+ )
1216
+ hidden_states = residual + hidden_states
1217
+
1218
+ # Fully Connected
1219
+ residual = hidden_states
1220
+ hidden_states = self.post_attention_layernorm(hidden_states)
1221
+
1222
+ if not self.use_async:
1223
+ sp_mask = self.sp_mlp(hidden_states)
1224
+
1225
+ # Compute distillation loss
1226
+ gating_output = self.mlp.sparse_act_fn(self.mlp.gate_proj(hidden_states))
1227
+ loss_func = MSELoss()
1228
+ self.distill_loss = loss_func(sp_mask, gating_output)
1229
+
1230
+ # Convert sp mask into binary form
1231
+ sp_mask = sp_mask > 0
1232
+
1233
+ if self.training:
1234
+ sp_mask = None
1235
+ # if not self.use_sparse_predictor:
1236
+ # sp_mask = None
1237
+
1238
+ hidden_states = self.mlp(hidden_states, sp_mask)
1239
+ hidden_states = residual + hidden_states
1240
+
1241
+ outputs = (hidden_states,)
1242
+
1243
+ if output_attentions:
1244
+ outputs += (self_attn_weights,)
1245
+
1246
+ if use_cache:
1247
+ outputs += (present_key_value,)
1248
+
1249
+ return outputs
1250
+
1251
+
1252
+ class SparseMistralConfig(MistralConfig):
1253
+ model_type = "sparse_mistral"
1254
+
1255
+ def __init__(self, **kwargs):
1256
+ super().__init__(**kwargs)
1257
+
1258
+
1259
+ class SparseMistralforCausalLM(MistralForCausalLM):
1260
+ config_class = SparseMistralConfig
1261
+
1262
+ def __init__(self, config):
1263
+ super().__init__(config)
1264
+ self.config = config
1265
+ if config.use_sparse_model:
1266
+ self.apply_sparse_mlp()
1267
+ if config.thresholds is not None:
1268
+ for idx, m in enumerate(self.model.layers):
1269
+ if isinstance(m.mlp, MistralSparseSiluMLP):
1270
+ m.mlp.dead_threshold = config.thresholds[idx]
1271
+ m.mlp.pre_mlp_threshold = getattr(
1272
+ config, "pre_mlp_thresholds", [0] * len(self.model.layers)
1273
+ )[idx]
1274
+ m.mlp.sparse_act_fn.set_new_threshold(m.mlp.dead_threshold)
1275
+ m.mlp.kill_sparse_swish_outputs = True
1276
+ m.mlp.use_relu = getattr(config, "use_relu", False)
1277
+ m.mlp.use_resilu = getattr(config, "use_resilu", False)
1278
+ if isinstance(
1279
+ m.self_attn,
1280
+ (SparseMistralAttention, SparseMistralFlashAttention),
1281
+ ):
1282
+ m.self_attn.pre_attn_threshold = config.pre_attn_thresholds[idx]
1283
+ if config.use_sparse_predictor:
1284
+ self.apply_sparse_predictor(init_svd=config.init_svd)
1285
+
1286
+ def apply_sparse_mlp(self):
1287
+ apply_mistral_sparse_silu_mlp(
1288
+ self,
1289
+ config=self.config,
1290
+ use_sparse_regularization=self.config.use_sparse_regularization,
1291
+ cut_pre_mlp=getattr(self.config, "cut_pre_mlp", False),
1292
+ cut_pre_attn=getattr(self.config, "cut_pre_attn", False),
1293
+ )
1294
+
1295
+ def apply_sparse_predictor(self, init_svd: bool = True):
1296
+ apply_mistral_sparse_decoder_layer(self, config=self.config, init_svd=init_svd)
1297
+
1298
+
1299
+ class GracefulRegularizationScheduler(TrainerCallback):
1300
+ def __init__(
1301
+ self,
1302
+ num_warmup_steps=40,
1303
+ is_enabled: bool = False,
1304
+ model_name: str = "mistral",
1305
+ test_dataset: Dataset = None,
1306
+ targeted_sparsity: float = 0.5,
1307
+ keep_regularization_with_kill: bool = False,
1308
+ ):
1309
+ """Scheduler for regularizing the model first before applying the dead threshold.
1310
+
1311
+ :param num_warmup_steps: number of training steps required to reach the dead threshold, defaults to 40
1312
+ :param increment_ratio: by how much to increase the dead threshold.
1313
+ For example, 0.5 means "increase the threshold by 0.5 * desired threshold
1314
+ """
1315
+ self.num_warmup_steps = num_warmup_steps
1316
+ self.is_enabled = is_enabled
1317
+ self.model_name = model_name
1318
+ self.test_dataset = test_dataset
1319
+ self.targeted_sparsity = targeted_sparsity
1320
+ self.keep_regularization_with_kill = keep_regularization_with_kill
1321
+ self.act_hist_path = (
1322
+ f"/matx/u/vxbrando/histograms/warm_up_reg_{targeted_sparsity}/act_hist.pt"
1323
+ )
1324
+ if self.is_enabled:
1325
+ print("GracefulRegularizationScheduler is enabled.")
1326
+ self.trainer = None
1327
+
1328
+ def set_trainer(self, trainer):
1329
+ self.trainer = trainer
1330
+
1331
+ def on_step_end(self, args, state, control, **kwargs):
1332
+ if not self.is_enabled:
1333
+ return
1334
+
1335
+ model = kwargs["model"]
1336
+ if isinstance(model, PeftModel):
1337
+ base_model = model.get_base_model()
1338
+ else:
1339
+ base_model = model
1340
+
1341
+ if state.global_step == 1:
1342
+ ds_print("Setting an initial reg threshold to 0.1")
1343
+ set_regularization_threshold(base_model, 0.1)
1344
+
1345
+ # if state.global_step >= self.num_warmup_steps and state.global_step % 50 == 0:
1346
+ if state.global_step == self.num_warmup_steps:
1347
+ activate_stats(base_model)
1348
+ enable_sparse_silu(base_model)
1349
+ self.trainer.evaluate()
1350
+ save_act_hist(base_model, self.act_hist_path)
1351
+ set_sparse_threshold(base_model, self.targeted_sparsity, True)
1352
+ deactivate_stats(base_model)
1353
+ self.trainer.use_sparse_regularization = self.keep_regularization_with_kill
1354
+ # set_layer_specific_regularization(model.get_base_model())
1355
+ print_dead_neuron_stats(model.get_base_model())
1356
+
1357
+ if state.global_step % 2000 == 0:
1358
+ if is_mainprocess():
1359
+ ds_print(
1360
+ f"Saving to /scr/lukeai/{self.model_name}_{state.global_step}.pt",
1361
+ )
1362
+ torch.save(
1363
+ model.state_dict(),
1364
+ f"/scr/lukeai/{self.model_name}_{state.global_step}.pt",
1365
+ )
1366
+
1367
+
1368
+ class GradualSparsificationScheduler(TrainerCallback):
1369
+ def __init__(
1370
+ self,
1371
+ num_warmup_steps=40,
1372
+ increment_ratio=0.5,
1373
+ is_enabled: bool = False,
1374
+ model_name: str = "mistral",
1375
+ ):
1376
+ """Scheduler for gradually increasing a dead threshold until it reaches the desired threshold.
1377
+
1378
+ :param num_warmup_steps: number of training steps required to reach the dead threshold, defaults to 40
1379
+ :param increment_ratio: by how much to increase the dead threshold.
1380
+ For example, 0.5 means "increase the threshold by 0.5 * desired threshold
1381
+ """
1382
+ self.num_warmup_steps = num_warmup_steps
1383
+ self.increment_ratio = increment_ratio
1384
+ self.step_size = int(num_warmup_steps * increment_ratio)
1385
+ self.is_enabled = is_enabled
1386
+ self.model_name = model_name
1387
+
1388
+ def on_step_end(self, args, state, control, **kwargs):
1389
+ model = kwargs["model"]
1390
+
1391
+ if not self.is_enabled:
1392
+ if state.global_step <= 10:
1393
+ for module in model.modules():
1394
+ if isinstance(module, MistralSparseSiluMLP):
1395
+ module.current_dead_threshold = module.dead_threshold
1396
+ return
1397
+
1398
+ current_dead_threshold = 0
1399
+ desired_dead_threshold = 0
1400
+
1401
+ if is_mainprocess():
1402
+ ds_print(state.global_step)
1403
+
1404
+ if state.global_step % self.step_size == 2:
1405
+ for module in model.modules():
1406
+ if isinstance(module, MistralSparseSiluMLP):
1407
+ desired_dead_threshold = copy.deepcopy(module.dead_threshold)
1408
+ current_dead_threshold = module.current_dead_threshold
1409
+ current_dead_threshold += (
1410
+ self.increment_ratio * desired_dead_threshold
1411
+ )
1412
+ module.current_dead_threshold = min(
1413
+ desired_dead_threshold, current_dead_threshold
1414
+ )
1415
+
1416
+ if is_running_deepspeed and is_mainprocess():
1417
+ ds_print(
1418
+ state.global_step,
1419
+ current_dead_threshold,
1420
+ desired_dead_threshold,
1421
+ )
1422
+
1423
+ if state.global_step % 2000 == 0:
1424
+ if is_running_deepspeed and is_mainprocess():
1425
+ ds_print(
1426
+ f"Saving to /matx/u/lukeai/{self.model_name}_{state.global_step - 2}.pt",
1427
+ )
1428
+ torch.save(
1429
+ model.state_dict(),
1430
+ f"/matx/u/lukeai/{self.model_name}_{state.global_step - 2}.pt",
1431
+ )
1432
+
1433
+
1434
+ def get_sparse_mistral_config(
1435
+ config: MistralConfig,
1436
+ use_sparse_model=False,
1437
+ use_sparse_predictor=False,
1438
+ use_sparse_regularization=False,
1439
+ thresholds=None,
1440
+ cut_pre_mlp=False,
1441
+ cut_pre_attn=False,
1442
+ ):
1443
+ new_config = SparseMistralConfig()
1444
+ new_config.__dict__.update(config.__dict__)
1445
+ config = new_config
1446
+ config.use_sparse_model = use_sparse_model
1447
+ config.use_sparse_predictor = use_sparse_predictor
1448
+ config.use_sparse_regularization = use_sparse_regularization
1449
+ config.thresholds = thresholds
1450
+ config.cut_pre_mlp = cut_pre_mlp
1451
+ config.cut_pre_attn = cut_pre_attn
1452
+
1453
+ return config
1454
+
1455
+
1456
+ def apply_mistral_sparse_silu_mlp(
1457
+ model,
1458
+ config,
1459
+ use_sparse_regularization: bool = False,
1460
+ use_flash_attn: bool = False,
1461
+ cut_pre_mlp: bool = False,
1462
+ cut_pre_attn: bool = False,
1463
+ ):
1464
+ for layer in model.model.layers:
1465
+ # counts += 1
1466
+ # if counts < 4:
1467
+ # continue
1468
+ original_mlp = layer.mlp
1469
+ new_mlp = MistralSparseSiluMLP(
1470
+ config, use_sparse_regularization=use_sparse_regularization
1471
+ )
1472
+ new_mlp.gate_proj = original_mlp.gate_proj
1473
+ new_mlp.up_proj = original_mlp.up_proj
1474
+ new_mlp.down_proj = original_mlp.down_proj
1475
+ new_mlp.cut_pre_mlp = cut_pre_mlp
1476
+ layer.mlp = new_mlp
1477
+ if cut_pre_attn:
1478
+ for layer in model.model.layers:
1479
+ original_attention = layer.self_attn
1480
+ if use_flash_attn:
1481
+ new_attention = SparseMistralFlashAttention(
1482
+ config=original_attention.config,
1483
+ layer_idx=original_attention.layer_idx,
1484
+ )
1485
+
1486
+ else:
1487
+ new_attention = SparseMistralAttention(
1488
+ config=original_attention.config,
1489
+ layer_idx=original_attention.layer_idx,
1490
+ )
1491
+ for attr in vars(original_attention):
1492
+ setattr(new_attention, attr, getattr(original_attention, attr))
1493
+ layer.self_attn = new_attention
1494
+
1495
+
1496
+ def apply_mistral_sparse_attention(
1497
+ model,
1498
+ config,
1499
+ ):
1500
+ for layer in model.model.layers:
1501
+ layer.self_attention = layer.self_attention
1502
+
1503
+
1504
+ def apply_mistral_sparse_decoder_layer(
1505
+ model,
1506
+ config,
1507
+ init_svd: bool = True,
1508
+ ):
1509
+ assert isinstance(model.model, MistralModel), "model.model must be a MistralModel."
1510
+ new_layers = []
1511
+ for layer_idx, layer in enumerate(model.model.layers):
1512
+ if isinstance(layer.mlp, MistralSparseSiluMLP):
1513
+ new_layers.append(
1514
+ SparseMistralDecoderLayer(
1515
+ config=config,
1516
+ layer_idx=layer_idx,
1517
+ decoder_layer=layer,
1518
+ init_svd=init_svd,
1519
+ )
1520
+ )
1521
+ print(f"{layer_idx}th mlp layer activation: {layer.mlp.sparse_act_fn}")
1522
+ else:
1523
+ new_layers.append(layer)
1524
+ model.model.layers = nn.ModuleList(new_layers)
1525
+
1526
+
1527
+ def enable_sparse_predictor(
1528
+ model,
1529
+ ):
1530
+ for layer_idx, layer in enumerate(model.model.layers):
1531
+ if isinstance(layer, MistralDecoderLayer):
1532
+ layer.use_sparse_predictor = True
1533
+
1534
+
1535
+ def disable_sparse_predictor(
1536
+ model,
1537
+ ):
1538
+ for layer_idx, layer in enumerate(model.model.layers):
1539
+ if isinstance(layer, MistralDecoderLayer):
1540
+ layer.use_sparse_predictor = False
1541
+
1542
+
1543
+ def activate_stats(model, is_collect_histogram: bool = True):
1544
+ for layer in model.model.layers:
1545
+ if isinstance(layer.mlp, MistralSparseSiluMLP):
1546
+ layer.mlp.activate_stats(is_collect_histogram=is_collect_histogram)
1547
+ if isinstance(
1548
+ layer.self_attn, (SparseMistralAttention, SparseMistralFlashAttention)
1549
+ ):
1550
+ layer.self_attn.activate_stats()
1551
+
1552
+
1553
+ def deactivate_stats(model):
1554
+ for layer in model.model.layers:
1555
+ if isinstance(layer.mlp, MistralSparseSiluMLP):
1556
+ layer.mlp.deactivate_stats()
1557
+ if isinstance(
1558
+ layer.self_attn, (SparseMistralAttention, SparseMistralFlashAttention)
1559
+ ):
1560
+ layer.self_attn.deactivate_stats()
1561
+
1562
+
1563
+ def enable_sparse_silu(model):
1564
+ print("Enabling SparseSilu")
1565
+ for i, layer in enumerate(model.model.layers):
1566
+ if isinstance(layer.mlp, MistralSparseSiluMLP):
1567
+ layer.mlp.kill_sparse_swish_outputs = True
1568
+
1569
+
1570
+ def print_dead_neuron_stats(model):
1571
+ total_sparsity = 0
1572
+ counts = 0
1573
+ for i, layer in enumerate(model.model.layers):
1574
+ if isinstance(layer.mlp, MistralSparseSiluMLP):
1575
+ dead_percentage = layer.mlp.dead_percentage * 100
1576
+ agg_sparsity = layer.mlp.agg_sparsity * 100
1577
+ pre_mlp_sparsity = layer.mlp.pre_mlp_sparsity * 100
1578
+ print(f"layer {i} sparsity: {dead_percentage:.3f}%")
1579
+ print(f"layer {i} agg sparsity: {agg_sparsity:.3f}%")
1580
+ print(f"layer {i} pre_mlp_sparsity: {pre_mlp_sparsity:.3f}%")
1581
+
1582
+ total_sparsity += dead_percentage
1583
+ counts += 1
1584
+ if isinstance(layer.self_attn, SparseMistralAttention) or isinstance(
1585
+ layer.self_attn, SparseMistralFlashAttention
1586
+ ):
1587
+ print(
1588
+ f"Attention layer {i} sparsity: {layer.self_attn.pre_attn_sparsity * 100: .3f}%"
1589
+ )
1590
+
1591
+ print(f"Total sparsity: {total_sparsity/counts: .3f}%")
1592
+ return total_sparsity / counts
1593
+
1594
+
1595
+ def get_sparse_layers(model: MistralModel):
1596
+ sparse_layers = [
1597
+ m.mlp for m in model.layers() if isinstance(m.mlp, MistralSparseSiluMLP)
1598
+ ]
1599
+ return sparse_layers
1600
+
1601
+
1602
+ def get_threshold(
1603
+ bin_edges: torch.tensor, histogram_counts: torch.tensor, sparsity_level: float
1604
+ ): # Only for L1 Regularization
1605
+ assert (
1606
+ len(bin_edges.shape) == len(histogram_counts.shape) == 1
1607
+ ), "bin_edges and histogram are expected to be 1-dimensional."
1608
+ histogram_counts /= histogram_counts.sum()
1609
+ threshold_idx = torch.searchsorted(
1610
+ histogram_counts.cumsum(0), sparsity_level, side="right"
1611
+ )
1612
+
1613
+ return bin_edges[threshold_idx]
1614
+
1615
+
1616
+ def set_regularization_threshold(model, threshold: float = 0.1):
1617
+ for i, layer in enumerate(model.model.layers):
1618
+ if (
1619
+ isinstance(layer.mlp, MistralSparseSiluMLP) and layer.mlp.is_stats
1620
+ ): # Can set the threshold only the relevant statistics is collected.
1621
+ layer.mlp.regularization_threshold = threshold # TODO: find better param
1622
+
1623
+
1624
+ def set_sparse_threshold(
1625
+ model,
1626
+ sparsity_level: float,
1627
+ use_relu: bool = False,
1628
+ use_resilu: bool = False,
1629
+ use_adaptive: bool = True,
1630
+ ):
1631
+ assert not (use_relu and use_resilu), "It's not allowed to use both relu and resilu"
1632
+ for i, layer in enumerate(model.model.layers):
1633
+ if (
1634
+ isinstance(layer.mlp, MistralSparseSiluMLP) and layer.mlp.is_stats
1635
+ ): # Can set the threshold only the relevant statistics is collected.
1636
+ if use_relu:
1637
+ layer.mlp.sparse_act_fn = nn.ReLU()
1638
+ layer.mlp.use_relu = True
1639
+ layer.mlp.use_resilu = False
1640
+ elif use_resilu:
1641
+ layer.mlp.sparse_act_fn = nn.Sequential(nn.ReLU(), nn.SiLU())
1642
+ layer.mlp.use_resilu = True
1643
+ layer.mlp.use_relu = False
1644
+ else:
1645
+ layer.mlp.dead_threshold = get_threshold(
1646
+ layer.mlp.histogram_bins,
1647
+ layer.mlp.post_act_hist_counts,
1648
+ sparsity_level,
1649
+ )
1650
+ layer.mlp.sparse_act_fn.set_new_threshold(layer.mlp.dead_threshold)
1651
+ layer.mlp.regularization_threshold = (
1652
+ layer.mlp.dead_threshold * 1.2
1653
+ ) # TODO: find better param
1654
+
1655
+ if layer.mlp.cut_pre_mlp:
1656
+ layer.mlp.pre_mlp_threshold = get_threshold(
1657
+ layer.mlp.histogram_bins,
1658
+ layer.mlp.pre_mlp_hist_counts,
1659
+ sparsity_level,
1660
+ )
1661
+ print(f"layer {i} pre-mlp threshold: {layer.mlp.pre_mlp_threshold}")
1662
+
1663
+ if isinstance(
1664
+ layer.self_attn, (SparseMistralAttention, SparseMistralFlashAttention)
1665
+ ):
1666
+ layer.self_attn.pre_attn_threshold = get_threshold(
1667
+ layer.self_attn.histogram_bins,
1668
+ layer.self_attn.pre_attn_hist_counts,
1669
+ sparsity_level,
1670
+ )
1671
+ print(f"layer {i} pre-attn threshold: {layer.self_attn.pre_attn_threshold}")
1672
+
1673
+
1674
+ def plot_histogram(
1675
+ bin_edges,
1676
+ histogram_counts: torch.tensor,
1677
+ title: str = "Activation Distribution",
1678
+ fig_dir: str = "figures",
1679
+ ):
1680
+ plt.bar(
1681
+ bin_edges[:-1], histogram_counts, width=np.diff(bin_edges), edgecolor="black"
1682
+ )
1683
+ plt.title(title)
1684
+ plt.xlabel("Activation Value")
1685
+ plt.ylabel("Frequency")
1686
+ os.makedirs(fig_dir, exist_ok=True)
1687
+ plt.savefig(f"{fig_dir}/{title}.png")
1688
+ # plt.show()
1689
+ plt.clf()
1690
+
1691
+
1692
+ def plot_act(model, fig_dir: str = "figures"):
1693
+ for i, layer in enumerate(model.model.layers):
1694
+ if (
1695
+ isinstance(layer.mlp, MistralSparseSiluMLP) and layer.mlp.is_stats
1696
+ ): # Can set the threshold only the relevant statistics is collected.
1697
+ plot_title = f"Layer: {i} Pre-Activation Distribution"
1698
+ plot_histogram(
1699
+ layer.mlp.histogram_bins, layer.mlp.pre_act_hist_counts, plot_title
1700
+ )
1701
+
1702
+ plot_title = f"Layer: {i} Post-Activation Distribution"
1703
+ plot_histogram(
1704
+ torch.nn.functional.silu(layer.mlp.histogram_bins),
1705
+ layer.mlp.pre_act_hist_counts,
1706
+ plot_title,
1707
+ )
1708
+
1709
+ plot_title = f"Layer: {i} Post-Activation Absolute Distribution"
1710
+ plot_histogram(
1711
+ layer.mlp.histogram_bins, layer.mlp.post_act_hist_counts, plot_title
1712
+ )
1713
+
1714
+
1715
+ def save_act_hist(model, dirname="/scr/jay/models/mistral/pre_finetune/cola_act_hist"):
1716
+ os.makedirs(dirname, exist_ok=True)
1717
+ act_dict = {}
1718
+ for i, layer in enumerate(model.model.layers):
1719
+ if (
1720
+ isinstance(layer.mlp, MistralSparseSiluMLP) and layer.mlp.is_stats
1721
+ ): # Can set the threshold only the relevant statistics is collected.
1722
+ act_dict[i] = (
1723
+ layer.mlp.histogram_bins,
1724
+ layer.mlp.pre_act_hist_counts,
1725
+ layer.mlp.post_act_hist_counts,
1726
+ layer.mlp.pre_mlp_hist_counts,
1727
+ )
1728
+ print("Saving activation histograms...\n\n\n")
1729
+ torch.save(act_dict, dirname + "/mlp_layers.pt")
1730
+
1731
+ act_dict = {}
1732
+ for i, layer in enumerate(model.model.layers):
1733
+ if (
1734
+ isinstance(layer.self_attn, SparseMistralAttention)
1735
+ and layer.self_attn.is_stats
1736
+ ): # Can set the threshold only the relevant statistics is collected.
1737
+ act_dict[i] = (
1738
+ layer.self_attn.histogram_bins,
1739
+ layer.self_attn.pre_attn_hist_counts,
1740
+ layer.self_attn.post_qk_hist_counts,
1741
+ )
1742
+ print("Saving activation histograms...\n\n\n")
1743
+ torch.save(act_dict, dirname + "/attn_layers.pt")
1744
+
1745
+
1746
+ def load_act_hist(model, dirname="/scr/jay/models/mistral/pre_finetune/cola_act_hist"):
1747
+ assert os.path.exists(
1748
+ dirname
1749
+ ), f"{dirname} does not exist when loading pre/post-activation histogram of SparseMistralSiluMLP."
1750
+ print("Loading activation histograms...\n\n\n")
1751
+
1752
+ act_dict = torch.load(dirname + "/mlp_layers.pt")
1753
+ for i, layer in enumerate(model.model.layers):
1754
+ if (
1755
+ isinstance(layer.mlp, MistralSparseSiluMLP) and layer.mlp.is_stats
1756
+ ): # Can set the threshold only the relevant statistics is collected.
1757
+ if len(act_dict[i]) == 4:
1758
+ (
1759
+ layer.mlp.histogram_bins,
1760
+ layer.mlp.pre_mlp_hist_counts,
1761
+ layer.mlp.pre_act_hist_counts,
1762
+ layer.mlp.post_act_hist_counts,
1763
+ ) = act_dict[i]
1764
+ else:
1765
+ (
1766
+ layer.mlp.histogram_bins,
1767
+ # layer.mlp.pre_mlp_hist_counts,
1768
+ layer.mlp.pre_act_hist_counts,
1769
+ layer.mlp.post_act_hist_counts,
1770
+ ) = act_dict[i]
1771
+ act_dict = torch.load(dirname + "/attn_layers.pt")
1772
+ for i, layer in enumerate(model.model.layers):
1773
+ if (
1774
+ isinstance(layer.self_attn, SparseMistralAttention)
1775
+ and layer.self_attn.is_stats
1776
+ ):
1777
+ (
1778
+ layer.self_attn.histogram_bins,
1779
+ layer.self_attn.pre_attn_hist_counts,
1780
+ layer.self_attn.post_qk_hist_counts,
1781
+ ) = act_dict[i]
1782
+
1783
+
1784
+ def enable_last_k_modules(model, start_module_idx: int):
1785
+ assert 32 > start_module_idx >= 0
1786
+ new_modules = []
1787
+ new_idx = 0
1788
+ for idx in range(start_module_idx, len(model.model.original_layers)):
1789
+ module = model.model.original_layers[idx]
1790
+ module.layer_idx = new_idx
1791
+ module.self_attn.layer_idx = new_idx
1792
+ new_modules.append(module)
1793
+ new_idx += 1
1794
+ print(module.layer_idx)
1795
+
1796
+ model.model.layers = nn.ModuleList(new_modules)
1797
+
1798
+
1799
+ def enable_first_k_modules(model, end_module_idx: int):
1800
+ assert 32 > end_module_idx >= 0
1801
+ new_modules = []
1802
+ new_idx = 0
1803
+ for idx in range(0, end_module_idx + 1):
1804
+ module = model.model.original_layers[idx]
1805
+ module.layer_idx = new_idx
1806
+ module.self_attn.layer_idx = new_idx
1807
+ new_modules.append(module)
1808
+ new_idx += 1
1809
+ print(module.layer_idx)
1810
+
1811
+ model.model.layers = nn.ModuleList(new_modules)