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