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