forked from microsoft/TransformerCompression
-
Notifications
You must be signed in to change notification settings - Fork 0
/
run_slicegpt_perplexity.py
executable file
·273 lines (227 loc) · 10.6 KB
/
run_slicegpt_perplexity.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import argparse
import logging
import os
import pathlib
import shutil
import torch
import wandb
from slicegpt import data_utils, gpu_utils, hf_utils, layernorm_fusion, rotate, utils
from slicegpt.config import config
from slicegpt.slicing_scheduler import ConstSlicingScheduler
utils.configure_logging()
os.environ["WANDB__SERVICE_WAIT"] = "300"
def argparser() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument(
"--model",
type=str,
default="facebook/opt-125m",
help="Model to load",
)
path_group = parser.add_mutually_exclusive_group()
path_group.add_argument(
"--model-path",
type=str,
default=None,
help="Path to load the model and tokenizer from (required for local models, not required for HF models)",
)
path_group.add_argument(
"--sliced-model-path",
type=str,
help="Path to load the model to fine-tune (sliced) and tokenizer from",
default=None,
)
parser.add_argument("--dtype", type=str, help="Data type to use.", choices=["fp32", "fp16"], default="fp16")
parser.add_argument(
"--cal-dataset",
type=str,
help="Dataset to calibrate and calculate perplexity on.",
choices=["wikitext2", "ptb", "c4", "alpaca"],
default="wikitext2",
)
parser.add_argument(
"--cal-nsamples",
type=int,
help="Number of samples of the calibration data to load.",
default=128,
)
parser.add_argument("--cal-batch-size", type=int, default=1, help="Batch size for loading the calibration data.")
parser.add_argument(
"--cal-max-seqlen", type=int, default=2048, help="Maximum sequence length for the calibration data."
)
parser.add_argument("--varied-seqlen", action="store_true", help="Varied sequence lengths in the calibration data.")
parser.add_argument("--seed", type=int, default=42, help="Seed for sampling the calibration data.")
parser.add_argument(
"--sparsity", type=float, default=0.0, help="A measure of how much slicing is applied (in the range [0, 1))"
)
parser.add_argument(
"--round-interval",
type=int,
default=8,
help="Interval for rounding the weights (the best value may depend on your hardware)",
)
parser.add_argument(
"--final-orientation",
type=str,
default="random",
choices=["random", "pca"],
help="Final orientation of the sliced weights.",
)
parser.add_argument(
"--ppl-eval-seqlen", type=int, default=2048, help="Sequence length for evaluating the perplexity."
)
parser.add_argument("--ppl-eval-batch-size", type=int, default=8, help="Batch size for evaluating the perplexity.")
parser.add_argument(
"--ppl-eval-nsamples", type=int, default=128, help="Number of samples to evaluate the perplexity on."
)
parser.add_argument("--eval-baseline", action="store_true", help="Evaluate the baseline model.")
parser.add_argument("--eval-fused-model", action="store_true", help="Evaluate the fused model.")
parser.add_argument("--ppl-only", action="store_true", help="Evaluate the loaded model without doing compression.")
parser.add_argument(
"--distribute-model",
action="store_true",
help="Use accelerate to put the model on multiple GPUs for evaluation. It is recommended to use it for models with 30B parameters and above.",
)
parser.add_argument("--save-dir", type=str, default=None, help="Path to save the model.")
parser.add_argument('--hf-token', type=str, default=os.getenv('HF_TOKEN', None))
parser.add_argument('--wandb-project', type=str, default="slicegpt", help="wandb project name.")
parser.add_argument('--no-wandb', action="store_true", help="Disable wandb.")
parser.add_argument(
'--device',
type=str,
default=None,
help="PyTorch device to use. Example values are 'cpu', 'cuda', 'cuda:0'. If not specified it will be defaulted to 'cuda' if available and 'cpu' otherwise.",
)
args = parser.parse_args()
logging.debug(f'Parsed arguments:')
for arg, argv in vars(args).items():
logging.debug(f'{arg} = {argv}')
if not 0 <= args.sparsity < 1:
raise argparse.ArgumentTypeError(f"Sparsity should be in the range [0, 1)")
if args.device:
config.device = torch.device(args.device)
if args.dtype == "fp16":
config.dtype = torch.float16
elif args.dtype == "fp32":
config.dtype = torch.float32
else:
raise argparse.ArgumentTypeError(f"Data type should be one of 'fp16', 'fp32'")
return args
def main() -> None:
logging.info("Running SliceGPT perplexity experiment")
args = argparser()
logging.info(f"PyTorch device: {config.device}")
logging.info(f"Number of available cuda devices: {torch.cuda.device_count()}")
try:
wandb.init(project=args.wandb_project, config=args, mode='disabled' if args.no_wandb else None)
except wandb.UsageError as e:
# wandb.init will throw an error if the user is not logged in and the process is running in a non-shell
# environment, e.g. notebook, IDE, no-shell process, etc. In this case, we want to continue without wandb.
logging.info(f'Failed to initialize wandb: {e}, continuing without wandb')
wandb.init(project=args.wandb_project, mode='disabled')
if args.sliced_model_path:
# load the model from sliced_model_path to compute perplexity and skip rotation and slicing
model_adapter, tokenizer = hf_utils.load_sliced_model(
args.model,
args.sliced_model_path,
sparsity=args.sparsity,
round_interval=args.round_interval,
token=args.hf_token,
)
else:
# load one of the pre-trained models
model_adapter, tokenizer = hf_utils.get_model_and_tokenizer(
args.model, args.model_path, token=args.hf_token, dtype=config.dtype
)
model = model_adapter.model
def reset_model_device() -> None:
if args.distribute_model:
# distribute model across available GPUs
gpu_utils.distribute_model(model_adapter)
else:
model.to(config.device)
dataset = data_utils.get_dataset(args.cal_dataset)
train_dataset, test_dataset = dataset["train"], dataset["test"]
train_loader = data_utils.prepare_dataloader(
dataset=train_dataset,
tokenizer=tokenizer,
max_seqlen=args.cal_max_seqlen,
batch_size=args.cal_batch_size,
nsamples=args.cal_nsamples,
varied_seqlen=args.varied_seqlen,
seed=args.seed,
)
test_loader = data_utils.prepare_test_dataloader(
dataset=test_dataset, tokenizer=tokenizer, batch_size=args.ppl_eval_batch_size
)
# evaluate perplexity and exit if sliced model is loaded or if ppl_only is set
if args.sliced_model_path or args.ppl_only:
reset_model_device()
dataset_ppl = gpu_utils.evaluate_ppl(model, model.config.pad_token_id, test_loader)
logging.info(f'Loaded model perplexity: {dataset_ppl}')
wandb.log({"original_ppl": dataset_ppl})
return
# original ppl
if args.eval_baseline:
reset_model_device()
dataset_ppl = gpu_utils.evaluate_ppl(model, model.config.pad_token_id, test_loader)
logging.info(f'Original ppl: {dataset_ppl:.4f}')
wandb.log({"original_ppl": dataset_ppl})
model.cpu()
utils.cleanup_memory()
# replace modules with compressible equivalents
layernorm_fusion.replace_layers(model_adapter)
# fuse layernorms and add rotations to skip connections
layernorm_fusion.fuse_modules(model_adapter)
# don't run this on large and/or distributed models
if args.eval_fused_model and not args.distribute_model:
model.to(config.device)
dataset_ppl = gpu_utils.evaluate_ppl(model, model.config.pad_token_id, test_loader)
logging.info(f'Post-fusion: {dataset_ppl:.4f}')
wandb.log({"post_fusion_ppl": dataset_ppl})
model.cpu()
# run GC and cleanup GPU memory
utils.cleanup_memory()
original_param_count = sum(int(p.nelement()) for p in model.parameters())
logging.info(f'Original model parameters: {original_param_count:,d}')
# compute new embedding dimension given the desired sparsity level
new_embedding_dimension = int((1 - args.sparsity) * model_adapter.hidden_size)
# round (down) to the nearest multiple of round_interval
new_embedding_dimension -= new_embedding_dimension % args.round_interval
logging.info(
f"New embedding dimension: {new_embedding_dimension} (sparsity {100*(1 - new_embedding_dimension / model_adapter.hidden_size):.4f} %)"
)
scheduler = ConstSlicingScheduler(new_embedding_dimension)
rotate.rotate_and_slice(model_adapter, train_loader, scheduler, final_orientation=args.final_orientation)
if args.save_dir:
sliced_model_dir = pathlib.Path(args.save_dir)
sliced_model_dir.mkdir(parents=True, exist_ok=True)
sliced_model_name = sliced_model_dir / f'{pathlib.Path(args.model).name}_{args.sparsity}.pt'
# Save the sliced model
torch.save(model.state_dict(), sliced_model_name)
# Save the slicing config
config_path = sliced_model_name.with_suffix('.json')
config_path.write_text(model_adapter.slicing_conf.to_json_string())
# If slicing a local model, also save HF config files in sliced model dir
if args.model_path:
try:
# copy all config files
for file in pathlib.Path(args.model_path).glob("*config*.json"):
shutil.copy(str(file), sliced_model_dir)
# copy all tokenizer files
for file in pathlib.Path(args.model_path).glob("*token*.json"):
shutil.copy(str(file), sliced_model_dir)
except OSError as e:
logging.info(f'Failed to copy configs and tokenizer files: {e}')
logging.info(f"Saved sliced model to {args.save_dir}")
reset_model_device()
dataset_ppl = gpu_utils.evaluate_ppl(model, model.config.pad_token_id, test_loader)
logging.info(f'After rotating and slicing {dataset_ppl:.4f}')
wandb.log({"sliced_ppl": dataset_ppl})
sliced_param_count = sum(int(p.nelement()) for p in model.parameters())
sliced_fraction = 1.0 - sliced_param_count / original_param_count
logging.info(f'Sliced model parameters: {sliced_param_count:,d} (sliced fraction {sliced_fraction:.4f})')
if __name__ == "__main__":
main()