gbai24 commited on
Commit
6815477
·
verified ·
1 Parent(s): 6cb9664

Upload 8 files

Browse files
Files changed (8) hide show
  1. LICENSE +201 -0
  2. README.md +104 -3
  3. datautils.py +106 -0
  4. llama_main.py +46 -0
  5. model_utils.py +831 -0
  6. opt_main.py +45 -0
  7. pruning_utils.py +324 -0
  8. quant.py +126 -0
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2024] [Guangji Bai]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md CHANGED
@@ -1,3 +1,104 @@
1
- ---
2
- license: apache-2.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # *SparseLLM*: Towards Global Pruning of LLMs
2
+
3
+ This repository contains the code for our **NeurIPS 2024** paper "[*SparseLLM*: Towards Global Pruning for Pre-trained Language Models](https://arxiv.org/abs/2402.17946)".
4
+
5
+ ## Updates
6
+
7
+ - <span style="color:green;">&#x2705;</span> *SparseLLM* code for both **OPT** and **LLaMA** models is now available.
8
+ - <span style="color:green;">&#x2705;</span> More model types and functionalities will be added soon.
9
+
10
+
11
+ ## Dependencies
12
+
13
+ This project requires the following core dependencies:
14
+
15
+ - `Python`: tested on v3.10.14
16
+ - `PyTorch`: tested on v2.4.1 with CUDA 12.2
17
+ - `Transformers`: tested on v4.45.1
18
+ - `Datasets`: tested on v3.0.1
19
+ - `numpy`: tested on v2.1.1
20
+ - `pandas`: tested on v2.2.3
21
+ - `huggingface_hub`: tested on v0.25.1
22
+ - `wandb`: tested on v0.18.2 (for experiment tracking)
23
+
24
+ ## Usage
25
+
26
+ The scripts directory contains all the bash commands to replicate the main results in our NeurIPS 2024 paper.
27
+
28
+ ### Example for Pruning OPT:
29
+
30
+ Below is an example command for pruning the OPT-125M model using SparseLLM, to achieve 70% sparsity.
31
+
32
+ ```
33
+ python opt_main.py \
34
+ --model facebook/opt-125m \
35
+ --dataset c4 \
36
+ --sparsity 0.7 \
37
+ ```
38
+
39
+ We provide a quick overview of the key arguments:
40
+
41
+ - `--model`: The identifier for the model on the Hugging Face model hub.
42
+ - `--dataset`: The dataset to use for evaluation. We support datasets like `c4`, `wikitext2`, and `ptb`.
43
+ - `--sparsity`: The desired sparsity level (percentage of weights to be pruned).
44
+
45
+ **Remark:** OPT-350M is currently not supported by our method, due to potential numerical stability issue.
46
+
47
+ ### Example for Pruning LLaMA-2:
48
+
49
+ For **LLaMA-2** models, use the llama_main.py file and specify the model path as `meta-llama/Llama-2-7b-hf`. Here is an example command for pruning LLaMA-2-7B:
50
+
51
+ ```
52
+ python llama_main.py \
53
+ --model meta-llama/Llama-2-7b-hf \
54
+ --dataset c4 \
55
+ --sparsity 0.7 \
56
+ ```
57
+
58
+ ### Available Sparsity Methods
59
+
60
+ We support the following pruning methods for both **OPT** and **LLaMA** models:
61
+
62
+ - **Unstructured**: Pruning individual weights without any specific pattern.
63
+ - **Semi-Structured N:M Sparsity**: For semi-structured pruning, use the following sparsity types:
64
+ - `--sparsity_type 2:4`: Prune 2 out of every 4 weights.
65
+ - `--sparsity_type 4:8`: Prune 4 out of every 8 weights.
66
+
67
+ ```
68
+ python opt_main.py \
69
+ --model facebook/opt-125m \
70
+ --dataset c4 \
71
+ --prunen 2 \
72
+ --prunem 4 \
73
+ ```
74
+
75
+ Similarly, for **LLaMA-2-7B** semi-structured pruning:
76
+
77
+ ```
78
+ python llama_main.py \
79
+ --model meta-llama/Llama-2-7b-hf \
80
+ --dataset c4 \
81
+ --prunen 2 \
82
+ --prunem 4 \
83
+ ```
84
+
85
+ ## Reference
86
+
87
+ If you find this code useful in your research, please consider citing:
88
+
89
+ ```bibtex
90
+ @article{bai2024gradient,
91
+ title={Gradient-Free Adaptive Global Pruning for Pre-trained Language Models},
92
+ author={Bai, Guangji and Li, Yijiang and Ling, Chen and Kim, Kibaek and Zhao, Liang},
93
+ journal={arXiv preprint arXiv:2402.17946},
94
+ year={2024}
95
+ }
96
+ ```
97
+ We sincerely appreciate it 😊
98
+
99
+ ## Disclaimer
100
+
101
+ 1. This repository is built upon the work introduced in the papers [SparseGPT](https://arxiv.org/abs/2301.00774) and [Wanda](https://arxiv.org/abs/2306.11695).
102
+ 2. *SparseLLM* aims to advance the research on improving fully local pruning methods for large language models (LLMs). Due to the iterative alternating optimization nature of *SparseLLM*, its running time will be longer than that of one-shot pruning methods (roughly number of iteration times) such as SparseGPT or Wanda. Additionally, the performance and numerical stability of the alternating optimization process can be sensitive to the initialization of hyperparameters.
103
+ 3. *SparseLLM* relies on auxiliary variables to achieve subproblem decomposition, which inevitably introduces additional memory overhead. For larger models like LLaMA-2-7B and beyond, we used a smaller calibration data size (e.g., 64 or 32) to ensure the code could run on an A100 40GB GPU. We are actively working on optimizing the GPU memory consumption and improving the efficiency of the code to support larger models and data sizes more effectively.
104
+
datautils.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DISCLAIMER: This file is a modified version of the original SparseGPT data loader. The original SparseGPT data loader can be found in [SparseGPT: Massive Language Models Can Be Accurately Pruned in One-Shot].
2
+
3
+ import random
4
+
5
+ import numpy as np
6
+ import torch
7
+ from datasets import load_dataset
8
+ from transformers import AutoTokenizer, LlamaTokenizer
9
+
10
+
11
+ def set_seed(seed):
12
+ np.random.seed(seed)
13
+ torch.random.manual_seed(seed)
14
+
15
+ def get_tokenizer(model):
16
+ if "llama" in model.lower():
17
+ tokenizer = LlamaTokenizer.from_pretrained(model, use_fast=False)
18
+ # fix for transformer 4.28.0.dev0 compatibility
19
+ if tokenizer.bos_token_id != 1 or tokenizer.eos_token_id != 2:
20
+ try:
21
+ tokenizer.bos_token_id = 1
22
+ tokenizer.eos_token_id = 2
23
+ except AttributeError:
24
+ pass
25
+ else:
26
+ tokenizer = AutoTokenizer.from_pretrained(model, use_fast=False)
27
+ return tokenizer
28
+
29
+ def get_wikitext2(nsamples, seed, seqlen, model, tokenizer):
30
+
31
+ traindata = load_dataset('wikitext', 'wikitext-2-raw-v1', split='train')
32
+ testdata = load_dataset('wikitext', 'wikitext-2-raw-v1', split='test')
33
+
34
+ trainenc = tokenizer(" ".join(traindata['text']), return_tensors='pt')
35
+ testenc = tokenizer("\n\n".join(testdata['text']), return_tensors='pt')
36
+
37
+ random.seed(seed)
38
+ trainloader = []
39
+ for _ in range(nsamples):
40
+ i = random.randint(0, trainenc.input_ids.shape[1] - seqlen - 1)
41
+ j = i + seqlen
42
+ inp = trainenc.input_ids[:, i:j]
43
+ tar = inp.clone()
44
+ tar[:, :-1] = -100
45
+ trainloader.append((inp, tar))
46
+ return trainloader, testenc
47
+
48
+ def get_ptb(nsamples, seed, seqlen, model, tokenizer):
49
+ traindata = load_dataset('ptb_text_only', 'penn_treebank', split='train')
50
+ testdata = load_dataset('ptb_text_only', 'penn_treebank', split='test')
51
+
52
+ trainenc = tokenizer(" ".join(traindata['sentence']), return_tensors='pt')
53
+ testenc = tokenizer(" ".join(testdata['sentence']), return_tensors='pt')
54
+
55
+ random.seed(seed)
56
+ trainloader = []
57
+ for _ in range(nsamples):
58
+ i = random.randint(0, trainenc.input_ids.shape[1] - seqlen - 1)
59
+ j = i + seqlen
60
+ inp = trainenc.input_ids[:, i:j]
61
+ tar = inp.clone()
62
+ tar[:, :-1] = -100
63
+ trainloader.append((inp, tar))
64
+ return trainloader, testenc
65
+
66
+ def get_c4(nsamples, seed, seqlen, model, tokenizer):
67
+ traindata = load_dataset(
68
+ 'allenai/c4', data_files={'train': 'en/c4-train.00000-of-01024.json.gz'}, split='train'
69
+ )
70
+ valdata = load_dataset(
71
+ 'allenai/c4', data_files={'validation': 'en/c4-validation.00000-of-00008.json.gz'}, split='validation'
72
+ )
73
+
74
+ random.seed(seed)
75
+ trainloader = []
76
+ for _ in range(nsamples):
77
+ while True:
78
+ i = random.randint(0, len(traindata) - 1)
79
+ trainenc = tokenizer(traindata[i]['text'], return_tensors='pt')
80
+ if trainenc.input_ids.shape[1] > seqlen:
81
+ break
82
+ i = random.randint(0, trainenc.input_ids.shape[1] - seqlen - 1)
83
+ j = i + seqlen
84
+ inp = trainenc.input_ids[:, i:j]
85
+ tar = inp.clone()
86
+ tar[:, :-1] = -100
87
+ trainloader.append((inp, tar))
88
+
89
+ valenc = tokenizer(' '.join(valdata[:1100]['text']), return_tensors='pt')
90
+ valenc = valenc.input_ids[:, :(256 * seqlen)]
91
+
92
+ class TokenizerWrapper:
93
+ def __init__(self, input_ids):
94
+ self.input_ids = input_ids
95
+ valenc = TokenizerWrapper(valenc)
96
+
97
+ return trainloader, valenc
98
+
99
+ def get_loaders(name, nsamples=128, seed=0, seqlen=2048, model=''):
100
+ tokenizer = get_tokenizer(model)
101
+ if 'wikitext2' in name:
102
+ return get_wikitext2(nsamples, seed, seqlen, model, tokenizer)
103
+ if 'ptb' in name:
104
+ return get_ptb(nsamples, seed, seqlen, model, tokenizer)
105
+ if 'c4' in name:
106
+ return get_c4(nsamples, seed, seqlen, model, tokenizer)
llama_main.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from model_utils import get_llama, llama_sparsellm, llama_eval
3
+ from datautils import get_loaders
4
+ import torch
5
+
6
+ def main():
7
+ parser = argparse.ArgumentParser()
8
+
9
+ # Arguments parsing
10
+ parser.add_argument("--model", type=str, default='meta-llama/Llama-2-7b-hf', help="LLaMA model to load")
11
+ parser.add_argument("--dataset", type=str, choices=["wikitext2", "ptb", "c4"], default="c4", help="Dataset for calibration.")
12
+ parser.add_argument("--seed", type=int, default=0, help="Seed for sampling calibration data.")
13
+ parser.add_argument("--nsamples", type=int, default=32, help="Number of calibration data samples.")
14
+ parser.add_argument("--percdamp", type=float, default=0.01, help="Percent of Hessian diagonal for dampening.")
15
+ parser.add_argument("--sparsity", type=float, default=0.5, help="Target sparsity.")
16
+ parser.add_argument("--prunen", type=int, default=0, help="N for N:M pruning.")
17
+ parser.add_argument("--prunem", type=int, default=0, help="M for N:M pruning.")
18
+ parser.add_argument("--blocksize", type=int, default=128, help="Blocksize for adaptive mask selection.")
19
+ parser.add_argument("--gmp", action="store_true", help="Run GMP baseline.")
20
+ parser.add_argument("--wbits", type=int, default=16, help="Quantization bits.")
21
+ parser.add_argument("--minlayer", type=int, default=-1, help="Prune layers with id >= this.")
22
+ parser.add_argument("--maxlayer", type=int, default=1000, help="Prune layers with id < this.")
23
+ parser.add_argument("--prune_only", type=str, default="", help="Prune only layers containing this text.")
24
+ parser.add_argument("--invert", action="store_true", help="Invert subset.")
25
+ parser.add_argument("--save", type=str, default="", help="Path to save model.")
26
+ parser.add_argument("--true-sequential", action="store_true", help="Run in true sequential mode.")
27
+ parser.add_argument("--log_wandb", action="store_true", help="Log to W&B.")
28
+
29
+ args = parser.parse_args()
30
+
31
+ model = get_llama(args)
32
+ model.eval()
33
+ dataloader, testloader = get_loaders(args.dataset, nsamples=args.nsamples, seed=args.seed, model=args.model, seqlen=model.seqlen)
34
+
35
+ if (args.sparsity or args.prunen) and not args.gmp:
36
+ llama_sparsellm(model, dataloader, torch.device('cuda'), args)
37
+
38
+ for dataset in ['wikitext2', 'ptb', 'c4']:
39
+ dataloader, testloader = get_loaders(dataset, seed=args.seed, model=args.model, seqlen=model.seqlen)
40
+ llama_eval(model, testloader, torch.device('cuda'), args, dataset)
41
+
42
+ if args.save:
43
+ model.save_pretrained(args.save)
44
+
45
+ if __name__ == '__main__':
46
+ main()
model_utils.py ADDED
@@ -0,0 +1,831 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file will contain functions related to the model such as loading the model, SparseLLM pruning, and evaluation.
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ from pruning_utils import *
6
+ from quant import *
7
+ import math
8
+ from transformers import OPTForCausalLM, LlamaForCausalLM
9
+
10
+ def get_opt(args):
11
+ def skip(*args, **kwargs):
12
+ pass
13
+ torch.nn.init.kaiming_uniform_ = skip
14
+ torch.nn.init.uniform_ = skip
15
+ torch.nn.init.normal_ = skip
16
+ model = OPTForCausalLM.from_pretrained(args.model, torch_dtype='auto')
17
+ model.seqlen = model.config.max_position_embeddings
18
+ return model
19
+
20
+ def get_llama(args):
21
+ def skip(*args, **kwargs):
22
+ pass
23
+ torch.nn.init.kaiming_uniform_ = skip
24
+ torch.nn.init.uniform_ = skip
25
+ torch.nn.init.normal_ = skip
26
+ model = LlamaForCausalLM.from_pretrained(args.model, torch_dtype='auto')
27
+ model.seqlen = 2048
28
+ return model
29
+
30
+ @torch.no_grad()
31
+ def opt_sparsellm(model, dataloader, dev, args):
32
+ print('Starting ...')
33
+
34
+ use_cache = model.config.use_cache
35
+ model.config.use_cache = False
36
+ layers = model.model.decoder.layers
37
+
38
+ model.model.decoder.embed_tokens = model.model.decoder.embed_tokens.to(dev)
39
+ model.model.decoder.embed_positions = model.model.decoder.embed_positions.to(dev)
40
+ if hasattr(model.model.decoder, 'project_out') and model.model.decoder.project_out:
41
+ model.model.decoder.project_out = model.model.decoder.project_out.to(dev)
42
+ if hasattr(model.model.decoder, 'project_in') and model.model.decoder.project_in:
43
+ model.model.decoder.project_in = model.model.decoder.project_in.to(dev)
44
+ layers[0] = layers[0].to(dev)
45
+
46
+ dtype = next(iter(model.parameters())).dtype
47
+ inps = torch.zeros(
48
+ (args.nsamples, model.seqlen, model.config.hidden_size), dtype=dtype, device=dev
49
+ )
50
+ cache = {'i': 0, 'attention_mask': None}
51
+
52
+ class Catcher(nn.Module):
53
+ def __init__(self, module):
54
+ super().__init__()
55
+ self.module = module
56
+ def forward(self, inp, **kwargs):
57
+ inps[cache['i']] = inp
58
+ cache['i'] += 1
59
+ cache['attention_mask'] = kwargs['attention_mask']
60
+ raise ValueError
61
+ layers[0] = Catcher(layers[0])
62
+ for batch in dataloader:
63
+ try:
64
+ model(batch[0].to(dev))
65
+ except ValueError:
66
+ pass
67
+ layers[0] = layers[0].module
68
+
69
+ layers[0] = layers[0].cpu()
70
+ model.model.decoder.embed_tokens = model.model.decoder.embed_tokens.cpu()
71
+ model.model.decoder.embed_positions = model.model.decoder.embed_positions.cpu()
72
+ if hasattr(model.model.decoder, 'project_out') and model.model.decoder.project_out:
73
+ model.model.decoder.project_out = model.model.decoder.project_out.cpu()
74
+ if hasattr(model.model.decoder, 'project_in') and model.model.decoder.project_in:
75
+ model.model.decoder.project_in = model.model.decoder.project_in.cpu()
76
+ torch.cuda.empty_cache()
77
+
78
+ outs = torch.zeros_like(inps)
79
+ attention_mask = cache['attention_mask']
80
+
81
+ print('Ready.')
82
+
83
+ for i in range(len(layers)):
84
+ layer = layers[i].to(dev)
85
+
86
+ subset = find_layers(layer)
87
+
88
+ gpts = {}
89
+ for name in subset:
90
+ if (not (args.minlayer <= i < args.maxlayer and args.prune_only in name)) == (not args.invert):
91
+ continue
92
+ gpts[name] = SparseGPT_OPT(subset[name])
93
+ if args.wbits < 16:
94
+ gpts[name].quantizer = Quantizer()
95
+ gpts[name].quantizer.configure(
96
+ args.wbits, perchannel=True, sym=False, mse=False
97
+ )
98
+
99
+ def add_batch(name):
100
+ def tmp(_, inp, out):
101
+ gpts[name].add_batch(inp[0].data, out.data, name)
102
+ return tmp
103
+ handles = []
104
+ for name in gpts:
105
+ handles.append(subset[name].register_forward_hook(add_batch(name)))
106
+ for j in range(args.nsamples):
107
+ outs[j] = layer(inps[j].unsqueeze(0), attention_mask=attention_mask)[0]
108
+ for h in handles:
109
+ h.remove()
110
+
111
+ target_layer_names = ['fc1', 'fc2']
112
+
113
+ for name in gpts:
114
+ if name not in target_layer_names:
115
+ print(i, name)
116
+ print('Pruning ...')
117
+ # Prune the layer
118
+ sparsity = args.sparsity
119
+ gpts[name].fasterprune(
120
+ sparsity, prunen=args.prunen, prunem=args.prunem, percdamp=args.percdamp, blocksize=args.blocksize
121
+ )
122
+ gpts[name].free()
123
+
124
+ # Adjust hyperparameters as needed
125
+ alpha = 5.0
126
+ beta = 5.0
127
+ gamma = 5.0
128
+
129
+ # Define the number of optimization steps
130
+ opt_epochs = 10
131
+
132
+ # Get the inputs and outputs which are constants here
133
+ X_list = gpts['fc1'].batch_inp
134
+ Y_list = gpts['fc2'].batch_out
135
+ X = torch.stack(X_list, dim=0)
136
+ Y = torch.stack(Y_list, dim=0)
137
+ # Reshape to 2D
138
+ X, Y = X.reshape((-1, X.size(-1))).T, Y.reshape((-1, Y.size(-1))).T
139
+
140
+ # free memory
141
+ X_list, Y_list = None, None
142
+ gpts['fc1'].batch_inp.clear()
143
+ gpts['fc2'].batch_out.clear()
144
+
145
+ hidden_z_list = gpts['fc1'].batch_out
146
+ z = torch.stack(hidden_z_list, dim=0)
147
+ hidden_z_list = None
148
+ gpts['fc1'].batch_out.clear()
149
+ hidden_p_list = gpts['fc2'].batch_inp
150
+ p = torch.stack(hidden_p_list, dim=0)
151
+ hidden_p_list = None
152
+ gpts['fc2'].batch_inp.clear()
153
+
154
+ # Initialize auxiliary variables z and p
155
+ z = z.reshape((-1, z.size(-1))).T.to(dev)
156
+ p = p.reshape((-1, p.size(-1))).T.to(dev)
157
+
158
+ torch.cuda.empty_cache()
159
+
160
+ # Pre-compute the pinverse of X and cache it to save computational cost
161
+ Xinv = torch.pinverse(X.to(dtype=torch.float32)).half()
162
+
163
+ for opt_step in range(opt_epochs):
164
+
165
+ ##############
166
+ # optimize W
167
+ ##############
168
+
169
+ if opt_step > 0: # for the first step, no need for updating W
170
+
171
+ # Update the weight matrix of fc1
172
+ bias = subset['fc1'].bias.unsqueeze(1).expand(-1, z.size(-1))
173
+ # Calculate the weight matrix
174
+ weight_matrix_1 = torch.matmul(z - bias, Xinv)
175
+ # assign the new parameters to gpts class
176
+ gpts['fc1'].layer.weight.copy_(weight_matrix_1)
177
+ del bias, weight_matrix_1
178
+
179
+ # Update the weight matrix of fc2
180
+ pinv = torch.pinverse(p.to(dtype=torch.float32)).half()
181
+ bias = subset['fc2'].bias.unsqueeze(1).expand(-1, Y.size(-1))
182
+ # Calculate the weight matrix
183
+ weight_matrix_2 = torch.matmul(Y - bias, pinv)
184
+ # assign the new parameters to gpts class
185
+ gpts['fc2'].layer.weight.copy_(weight_matrix_2)
186
+
187
+ del bias, weight_matrix_2, pinv
188
+ torch.cuda.empty_cache()
189
+
190
+ ##############
191
+ # prune W
192
+ ##############
193
+
194
+ # modify gpts[name].H to be our auxiliary variable
195
+ if opt_step > 0: # for the first step, no need for updating H
196
+
197
+ tmp_H = torch.zeros_like(gpts['fc2'].H)
198
+ tmp_p = p.T.reshape((args.nsamples, -1, p.size(0)))
199
+ tmp_nsamples = 0
200
+ for j in range(args.nsamples):
201
+ tmp_inp = tmp_p[j].unsqueeze(0)
202
+ tmp = tmp_inp.shape[0]
203
+ if isinstance(gpts['fc2'].layer, nn.Linear) or isinstance(gpts['fc2'].layer, transformers.Conv1D):
204
+ if len(tmp_inp.shape) == 3:
205
+ tmp_inp = tmp_inp.reshape((-1, tmp_inp.shape[-1]))
206
+ tmp_inp = tmp_inp.t()
207
+ tmp_H *= tmp_nsamples / (tmp_nsamples + tmp)
208
+ tmp_nsamples += tmp
209
+ tmp_inp = math.sqrt(2 / tmp_nsamples) * tmp_inp.float()
210
+ tmp_H += tmp_inp.matmul(tmp_inp.t())
211
+ gpts['fc2'].H.copy_(tmp_H)
212
+ del tmp_H, tmp_p
213
+ torch.cuda.empty_cache()
214
+
215
+ for name in target_layer_names:
216
+ print(i, name)
217
+ print('Pruning ...')
218
+ sparsity = args.sparsity
219
+ gpts[name].fasterprune(
220
+ sparsity, prunen=args.prunen, prunem=args.prunem, percdamp=args.percdamp, blocksize=args.blocksize
221
+ )
222
+
223
+ ##############
224
+ # optimize p
225
+ ##############
226
+
227
+ # Activation inverse
228
+ next_weight = subset['fc2'].weight
229
+ m1 = beta * torch.matmul(next_weight.T, next_weight)
230
+ m2 = gamma * torch.eye(m1.shape[0], device=m1.device)
231
+ av = torch.inverse(m1 + m2).to(dtype=torch.float16)
232
+
233
+ del m1, m2
234
+ torch.cuda.empty_cache()
235
+
236
+ # Calculate ReLU
237
+ layer_nl_output = nn.functional.relu(z)
238
+
239
+ # Activation formulate
240
+ bias = subset['fc2'].bias.unsqueeze(1).expand(-1, Y.size(-1))
241
+ m3 = beta * torch.matmul(next_weight.T, Y - bias)
242
+ m4 = gamma * layer_nl_output
243
+ af = m3 + m4
244
+
245
+ p = torch.matmul(av, af)
246
+
247
+ del layer_nl_output, next_weight, av, m3, m4, af, bias
248
+ torch.cuda.empty_cache()
249
+
250
+ ##############
251
+ # optimize z
252
+ ##############
253
+
254
+ w = subset['fc1'].weight
255
+ bias = subset['fc1'].bias.unsqueeze(1).expand(-1, z.size(-1))
256
+ m = torch.matmul(w, X) + bias
257
+ sol1 = (gamma * p + alpha * m) / (gamma + alpha)
258
+ sol2 = m
259
+ del w, bias
260
+ torch.cuda.empty_cache()
261
+
262
+ z1 = torch.zeros_like(p)
263
+ z2 = torch.zeros_like(p)
264
+
265
+ chunk_size = 500 # Choose an appropriate size based on your memory constraints
266
+ # Assuming the first dimension is the one to be chunked
267
+ for k in range(0, sol1.size(0), chunk_size):
268
+ chunk = slice(k, k + chunk_size)
269
+
270
+ # Apply the condition and assignment for the chunk
271
+ z1_chunk = z1[chunk]
272
+ sol1_chunk = sol1[chunk]
273
+ z1_chunk[sol1_chunk >= 0.] = sol1_chunk[sol1_chunk >= 0.]
274
+ z1[chunk] = z1_chunk
275
+
276
+ z2_chunk = z2[chunk]
277
+ sol2_chunk = sol2[chunk]
278
+ z2_chunk[sol2_chunk <= 0.] = sol2_chunk[sol2_chunk <= 0.]
279
+ z2[chunk] = z2_chunk
280
+
281
+ del z1_chunk, z2_chunk, sol1_chunk, sol2_chunk, sol1, sol2
282
+ torch.cuda.empty_cache()
283
+
284
+ for k in range(0, z1.size(0), chunk_size):
285
+ chunk = slice(k, k + chunk_size)
286
+
287
+ # Compute fz_1 and fz_2 for the current chunk
288
+ fz_1_chunk = gamma * torch.square(p[chunk] - nn.functional.relu(z1[chunk])) + alpha * torch.square(z1[chunk] - m[chunk])
289
+ fz_2_chunk = gamma * torch.square(p[chunk] - nn.functional.relu(z2[chunk])) + alpha * torch.square(z2[chunk] - m[chunk])
290
+
291
+ # Determine indices for z1 and z2 for the current chunk
292
+ index_z1_chunk = fz_1_chunk <= fz_2_chunk
293
+ index_z2_chunk = fz_2_chunk < fz_1_chunk
294
+
295
+ # Update z for the current chunk
296
+ z[chunk][index_z1_chunk] = z1[chunk][index_z1_chunk]
297
+ z[chunk][index_z2_chunk] = z2[chunk][index_z2_chunk]
298
+
299
+ # Clear memory if necessary
300
+ del fz_1_chunk, fz_2_chunk, index_z1_chunk, index_z2_chunk, z1, z2, m, chunk
301
+ torch.cuda.empty_cache()
302
+
303
+ for name in target_layer_names:
304
+ gpts[name].free()
305
+
306
+ for j in range(args.nsamples):
307
+ outs[j] = layer(inps[j].unsqueeze(0), attention_mask=attention_mask)[0]
308
+
309
+ layers[i] = layer.cpu()
310
+ del layer
311
+ torch.cuda.empty_cache()
312
+
313
+ inps, outs = outs, inps
314
+
315
+ model.config.use_cache = use_cache
316
+
317
+
318
+ @torch.no_grad()
319
+ def llama_sparsellm(model, dataloader, dev, args):
320
+ print("Starting...")
321
+
322
+ use_cache = model.config.use_cache
323
+ model.config.use_cache = False
324
+ layers = model.model.layers
325
+
326
+ model.model.embed_tokens = model.model.embed_tokens.to(dev)
327
+ model.model.norm = model.model.norm.to(dev)
328
+ layers[0] = layers[0].to(dev)
329
+
330
+ dtype = next(iter(model.parameters())).dtype
331
+ inps = torch.zeros(
332
+ (args.nsamples, model.seqlen, model.config.hidden_size), dtype=dtype, device=dev
333
+ )
334
+ cache = {"i": 0, "attention_mask": None}
335
+
336
+ class Catcher(nn.Module):
337
+ def __init__(self, module):
338
+ super().__init__()
339
+ self.module = module
340
+
341
+ def forward(self, inp, **kwargs):
342
+ inps[cache["i"]] = inp
343
+ cache["i"] += 1
344
+ cache["attention_mask"] = kwargs["attention_mask"]
345
+ raise ValueError
346
+
347
+ layers[0] = Catcher(layers[0])
348
+ for batch in dataloader:
349
+ try:
350
+ model(batch[0].to(dev))
351
+ except ValueError:
352
+ pass
353
+ layers[0] = layers[0].module
354
+
355
+ layers[0] = layers[0].cpu()
356
+ model.model.embed_tokens = model.model.embed_tokens.cpu()
357
+ model.model.norm = model.model.norm.cpu()
358
+ torch.cuda.empty_cache()
359
+
360
+ outs = torch.zeros_like(inps)
361
+ attention_mask = cache["attention_mask"]
362
+
363
+ print("Ready.")
364
+
365
+ for i in range(len(layers)):
366
+ layer = layers[i].to(dev)
367
+ full = find_layers(layer)
368
+
369
+ if args.true_sequential:
370
+ sequential = [
371
+ ["self_attn.k_proj", "self_attn.v_proj", "self_attn.q_proj"],
372
+ ["self_attn.o_proj"],
373
+ ["mlp.up_proj", "mlp.gate_proj"],
374
+ ["mlp.down_proj"],
375
+ ]
376
+ else:
377
+ sequential = [list(full.keys())]
378
+
379
+ for names in sequential:
380
+ subset = {n: full[n] for n in names}
381
+
382
+ gpts = {}
383
+ for name in subset:
384
+ if (
385
+ not (args.minlayer <= i < args.maxlayer and args.prune_only in name)
386
+ ) == (not args.invert):
387
+ continue
388
+ gpts[name] = SparseGPT_LlaMA(subset[name])
389
+ if args.wbits < 16:
390
+ gpts[name].quantizer = Quantizer()
391
+ gpts[name].quantizer.configure(
392
+ args.wbits, perchannel=True, sym=False, mse=False
393
+ )
394
+
395
+ def add_batch(name):
396
+ def tmp(_, inp, out):
397
+ gpts[name].add_batch(inp[0].data, out.data, name)
398
+
399
+ return tmp
400
+
401
+ handles = []
402
+ for name in subset:
403
+ handles.append(subset[name].register_forward_hook(add_batch(name)))
404
+ for j in range(args.nsamples):
405
+ outs[j] = layer(inps[j].unsqueeze(0), attention_mask=attention_mask)[0]
406
+ for h in handles:
407
+ h.remove()
408
+
409
+ target_layer_names = ["mlp.up_proj", "mlp.gate_proj", "mlp.down_proj"]
410
+
411
+ for name in subset:
412
+ if name not in target_layer_names:
413
+ print(i, name)
414
+ print("Pruning ...")
415
+ sparsity = args.sparsity
416
+ gpts[name].fasterprune(
417
+ sparsity,
418
+ prunen=args.prunen,
419
+ prunem=args.prunem,
420
+ percdamp=args.percdamp,
421
+ blocksize=args.blocksize,
422
+ )
423
+ gpts[name].free()
424
+
425
+ # Adjust hyperparameters as needed
426
+ alpha = 5.0
427
+ beta = 5.0
428
+ gamma = 5.0
429
+
430
+ # Define the number of global pruning epochs
431
+ opt_epochs = 8 # This might need to be adjusted
432
+
433
+ # Get the inputs and outputs which are constants here
434
+ X_list = gpts['mlp.up_proj'].batch_inp
435
+ Y_list = gpts['mlp.down_proj'].batch_out
436
+ X = torch.stack(X_list, dim=0)
437
+ Y = torch.stack(Y_list, dim=0)
438
+ # Reshape to 2D
439
+ X, Y = X.reshape((-1, X.size(-1))).T, Y.reshape((-1, Y.size(-1))).T
440
+
441
+ # free memory
442
+ X_list, Y_list = None, None
443
+ gpts['mlp.up_proj'].batch_inp.clear()
444
+ gpts['mlp.down_proj'].batch_out.clear()
445
+
446
+ # Get the hidden variables and their initialization
447
+ # z: output of 'mlp.up_proj'
448
+ hidden_z_list = gpts['mlp.up_proj'].batch_out
449
+ z = torch.stack(hidden_z_list, dim=0)
450
+ hidden_z_list = None
451
+ gpts['mlp.up_proj'].batch_out.clear()
452
+ # p: input of 'mlp.down_proj'
453
+ hidden_p_list = gpts['mlp.down_proj'].batch_inp
454
+ p = torch.stack(hidden_p_list, dim=0)
455
+ hidden_p_list = None
456
+ gpts['mlp.down_proj'].batch_inp.clear()
457
+ # s: output of 'mlp.gate_proj'
458
+ hidden_s_list = gpts['mlp.gate_proj'].batch_out
459
+ s = torch.stack(hidden_s_list, dim=0)
460
+ hidden_s_list = None
461
+ gpts['mlp.gate_proj'].batch_out.clear()
462
+
463
+ # Reshape auxiliary variables
464
+ z = z.reshape((-1, z.size(-1))).T.to(dev)
465
+ p = p.reshape((-1, p.size(-1))).T.to(dev)
466
+ s = s.reshape((-1, s.size(-1))).T.to(dev)
467
+
468
+ torch.cuda.empty_cache()
469
+
470
+ # Pre-compute the pinverse of X and cache it to save computational cost
471
+ Xinv = torch.pinverse(X.to(dtype=torch.float32)).half()
472
+
473
+ # list to store training losses
474
+ training_loss = {'Y_p_loss': [], 'p_z_loss': [], 'z_X_loss': [], 'train_loss': []}
475
+
476
+ for opt_step in range(opt_epochs):
477
+
478
+ ##############
479
+ # optimize W
480
+ ##############
481
+
482
+ if opt_step > 0: # for the first step, no need for updating W
483
+
484
+ # Update the weight matrix of mlp.up_project
485
+ # Calculate the weight matrix
486
+ weight_matrix_1 = torch.matmul(z, Xinv)
487
+ # assign the new parameters to gpts class
488
+ gpts['mlp.up_proj'].layer.weight.copy_(weight_matrix_1)
489
+ del weight_matrix_1
490
+
491
+ # Update the weight matrix of mlp.down_proj
492
+ pinv = torch.pinverse(p.to(dtype=torch.float32)).half()
493
+ # Calculate the weight matrix
494
+ weight_matrix_2 = torch.matmul(Y, pinv)
495
+ # assign the new parameters to gpts class
496
+ gpts['mlp.down_proj'].layer.weight.copy_(weight_matrix_2)
497
+ del weight_matrix_2, pinv
498
+
499
+ # Update the weight matrix of mlp.gate_project
500
+ # Calculate the weight matrix
501
+ weight_matrix_3 = torch.matmul(s, Xinv)
502
+ # assign the new parameters to gpts class
503
+ gpts['mlp.gate_proj'].layer.weight.copy_(weight_matrix_3)
504
+ del weight_matrix_3
505
+
506
+ torch.cuda.empty_cache()
507
+
508
+ ##############
509
+ # prune W
510
+ ##############
511
+
512
+ # modify gpts[name].H to be our auxiliary variable
513
+ if opt_step > 0: # for the first step, no need for updating H
514
+
515
+ tmp_H = torch.zeros_like(gpts['mlp.down_proj'].H)
516
+ tmp_p = p.T.reshape((args.nsamples, -1, p.size(0)))
517
+ tmp_nsamples = 0
518
+ for j in range(args.nsamples):
519
+ tmp_inp = tmp_p[j].unsqueeze(0)
520
+ tmp = tmp_inp.shape[0]
521
+ if isinstance(gpts['mlp.down_proj'].layer, nn.Linear) or isinstance(gpts['mlp.down_proj'].layer, transformers.Conv1D):
522
+ if len(tmp_inp.shape) == 3:
523
+ tmp_inp = tmp_inp.reshape((-1, tmp_inp.shape[-1]))
524
+ tmp_inp = tmp_inp.t()
525
+ tmp_H *= tmp_nsamples / (tmp_nsamples + tmp)
526
+ tmp_nsamples += tmp
527
+ tmp_inp = math.sqrt(2 / tmp_nsamples) * tmp_inp.float()
528
+ tmp_H += tmp_inp.matmul(tmp_inp.t())
529
+ gpts['mlp.down_proj'].H.copy_(tmp_H)
530
+ del tmp_H, tmp_p
531
+ torch.cuda.empty_cache()
532
+
533
+ for name in target_layer_names:
534
+ print(i, name)
535
+ print('Pruning ...')
536
+ sparsity = args.sparsity
537
+ gpts[name].fasterprune(
538
+ sparsity,
539
+ prunen=args.prunen,
540
+ prunem=args.prunem,
541
+ percdamp=args.percdamp,
542
+ blocksize=args.blocksize,
543
+ )
544
+
545
+ ##############
546
+ # optimize p
547
+ ##############
548
+
549
+ # Activation inverse
550
+ next_weight = subset['mlp.down_proj'].weight
551
+ m1 = beta * torch.matmul(next_weight.T, next_weight)
552
+ m2 = gamma * torch.eye(m1.shape[0], device=m1.device)
553
+ av = torch.inverse(m1 + m2).to(dtype=torch.float16)
554
+
555
+ del m1, m2
556
+ torch.cuda.empty_cache()
557
+
558
+ # Calculate SwiGLU output
559
+ layer_nl_output = nn.functional.silu(s) * z
560
+
561
+ # Activation formulate
562
+ m3 = beta * torch.matmul(next_weight.T, Y)
563
+ m4 = gamma * layer_nl_output
564
+ af = m3 + m4
565
+
566
+ p = torch.matmul(av, af)
567
+
568
+ del layer_nl_output, next_weight, av, m3, m4, af
569
+ torch.cuda.empty_cache()
570
+
571
+ ##############
572
+ # optimize z
573
+ ##############
574
+
575
+ w = subset['mlp.up_proj'].weight
576
+ m = torch.matmul(w, X)
577
+ swish = nn.functional.silu(s)
578
+ z = (m + swish * p) / (swish ** 2 + 1)
579
+
580
+ del w, m, swish
581
+ torch.cuda.empty_cache()
582
+
583
+ ##############
584
+ # optimize s
585
+ ##############
586
+
587
+ w = subset['mlp.gate_proj'].weight
588
+ # convert the layer's weight tensor to float32 and enable grad
589
+ w = w.to(dtype=torch.float32).requires_grad_(True)
590
+
591
+ s_update_epochs = 2
592
+ s_learning_rate = 0.01
593
+ for _ in range(s_update_epochs):
594
+
595
+ batch_size = 1000 # Choose an appropriate batch size based on your memory constraints
596
+ # s: [hidden_d, n_samples]
597
+ for k in range(0, s.size(-1), batch_size):
598
+ chunk = slice(k, k + batch_size)
599
+
600
+ # get the "mini-batch" for each tensor and turn on autograd
601
+ X_batch = X[:,chunk].to(dtype=torch.float32).requires_grad_(True)
602
+ z_batch = z[:,chunk].to(dtype=torch.float32).requires_grad_(True)
603
+ p_batch = p[:,chunk].to(dtype=torch.float32).requires_grad_(True)
604
+ s_batch = s[:,chunk].to(dtype=torch.float32).requires_grad_(True)
605
+
606
+ with torch.enable_grad(): # temporarily turn on the Pytorch computational graph functionality
607
+
608
+ loss_s = alpha * torch.norm(s_batch - torch.matmul(w, X_batch))**2
609
+ loss_s += gamma * torch.norm(p_batch - nn.functional.silu(s_batch) * z_batch)**2
610
+
611
+ loss_s.backward()
612
+ s_batch -= s_learning_rate * s_batch.grad
613
+ s_batch.grad.zero_()
614
+ s[:,chunk] = s_batch.detach().to(dtype=torch.float16)
615
+
616
+ s_batch, X_batch, z_batch, p_batch, w = s_batch.detach(), X_batch.detach(), z_batch.detach(), p_batch.detach(), w.detach()
617
+ del w, loss_s, s_batch, X_batch, z_batch, p_batch
618
+ torch.cuda.empty_cache()
619
+
620
+ # compute and save the training loss after each epoch
621
+ tmp_training_loss = nn.functional.mse_loss(torch.matmul(subset['mlp.down_proj'].weight,
622
+ nn.functional.silu(torch.matmul(subset['mlp.gate_proj'].weight, X))
623
+ * torch.matmul(subset['mlp.up_proj'].weight, X)), Y)
624
+ training_loss['train_loss'].append(tmp_training_loss.item())
625
+
626
+ for j in range(args.nsamples):
627
+ outs[j] = layer(inps[j].unsqueeze(0), attention_mask=attention_mask)[0]
628
+
629
+ layers[i] = layer.cpu()
630
+ del layer
631
+ del gpts
632
+ torch.cuda.empty_cache()
633
+
634
+ inps, outs = outs, inps
635
+
636
+ model.config.use_cache = use_cache
637
+
638
+
639
+ @torch.no_grad()
640
+ def opt_eval(model, testenc, dev, args, dataset: str):
641
+ print('Evaluating ...')
642
+
643
+ testenc = testenc.input_ids
644
+ nsamples = testenc.numel() // model.seqlen
645
+
646
+ use_cache = model.config.use_cache
647
+ model.config.use_cache = False
648
+ layers = model.model.decoder.layers
649
+
650
+ model.model.decoder.embed_tokens = model.model.decoder.embed_tokens.to(dev)
651
+ model.model.decoder.embed_positions = model.model.decoder.embed_positions.to(dev)
652
+ if hasattr(model.model.decoder, 'project_out') and model.model.decoder.project_out:
653
+ model.model.decoder.project_out = model.model.decoder.project_out.to(dev)
654
+ if hasattr(model.model.decoder, 'project_in') and model.model.decoder.project_in:
655
+ model.model.decoder.project_in = model.model.decoder.project_in.to(dev)
656
+ layers[0] = layers[0].to(dev)
657
+
658
+ dtype = next(iter(model.parameters())).dtype
659
+ inps = torch.zeros(
660
+ (nsamples, model.seqlen, model.config.hidden_size), dtype=dtype, device=dev
661
+ )
662
+ cache = {'i': 0, 'attention_mask': None}
663
+
664
+ class Catcher(nn.Module):
665
+ def __init__(self, module):
666
+ super().__init__()
667
+ self.module = module
668
+ def forward(self, inp, **kwargs):
669
+ inps[cache['i']] = inp
670
+ cache['i'] += 1
671
+ cache['attention_mask'] = kwargs['attention_mask']
672
+ raise ValueError
673
+ layers[0] = Catcher(layers[0])
674
+ for i in range(nsamples):
675
+ batch = testenc[:, (i * model.seqlen):((i + 1) * model.seqlen)].to(dev)
676
+ try:
677
+ model(batch)
678
+ except ValueError:
679
+ pass
680
+ layers[0] = layers[0].module
681
+
682
+ layers[0] = layers[0].cpu()
683
+ model.model.decoder.embed_tokens = model.model.decoder.embed_tokens.cpu()
684
+ model.model.decoder.embed_positions = model.model.decoder.embed_positions.cpu()
685
+ if hasattr(model.model.decoder, 'project_out') and model.model.decoder.project_out:
686
+ model.model.decoder.project_out = model.model.decoder.project_out.cpu()
687
+ if hasattr(model.model.decoder, 'project_in') and model.model.decoder.project_in:
688
+ model.model.decoder.project_in = model.model.decoder.project_in.cpu()
689
+ torch.cuda.empty_cache()
690
+
691
+ outs = torch.zeros_like(inps)
692
+ attention_mask = cache['attention_mask']
693
+
694
+ for i in range(len(layers)):
695
+ print(i)
696
+ layer = layers[i].to(dev)
697
+
698
+ if args.gmp:
699
+ subset = find_layers(layer)
700
+ for name in subset:
701
+ W = subset[name].weight.data
702
+ thresh = torch.sort(torch.abs(W.flatten()))[0][int(W.numel() * args.sparsity)]
703
+ W.data[torch.abs(W.data) <= thresh] = 0
704
+
705
+ for j in range(nsamples):
706
+ outs[j] = layer(inps[j].unsqueeze(0), attention_mask=attention_mask)[0]
707
+ layers[i] = layer.cpu()
708
+ del layer
709
+ torch.cuda.empty_cache()
710
+ inps, outs = outs, inps
711
+
712
+ if model.model.decoder.final_layer_norm is not None:
713
+ model.model.decoder.final_layer_norm = model.model.decoder.final_layer_norm.to(dev)
714
+ if model.model.decoder.project_out is not None:
715
+ model.model.decoder.project_out = model.model.decoder.project_out.to(dev)
716
+ model.lm_head = model.lm_head.to(dev)
717
+
718
+ testenc = testenc.to(dev)
719
+ nlls = []
720
+ for i in range(nsamples):
721
+ hidden_states = inps[i].unsqueeze(0)
722
+ if model.model.decoder.final_layer_norm is not None:
723
+ hidden_states = model.model.decoder.final_layer_norm(hidden_states)
724
+ if model.model.decoder.project_out is not None:
725
+ hidden_states = model.model.decoder.project_out(hidden_states)
726
+ lm_logits = model.lm_head(hidden_states)
727
+ shift_logits = lm_logits[:, :-1, :].contiguous()
728
+ shift_labels = testenc[
729
+ :, (i * model.seqlen):((i + 1) * model.seqlen)
730
+ ][:, 1:]
731
+ loss_fct = nn.CrossEntropyLoss()
732
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
733
+ neg_log_likelihood = loss.float() * model.seqlen
734
+ nlls.append(neg_log_likelihood)
735
+ ppl = torch.exp(torch.stack(nlls).sum() / (nsamples * model.seqlen))
736
+ print(f"Perplexity: {ppl.item():3f}")
737
+
738
+ model.config.use_cache = use_cache
739
+
740
+
741
+
742
+ @torch.no_grad()
743
+ def llama_eval(model, testenc, dev, args, dataset: str):
744
+ print("Evaluating ...")
745
+
746
+ testenc = testenc.input_ids
747
+ nsamples = testenc.numel() // model.seqlen
748
+
749
+ use_cache = model.config.use_cache
750
+ model.config.use_cache = False
751
+ layers = model.model.layers
752
+
753
+ model.model.embed_tokens = model.model.embed_tokens.to(dev)
754
+ layers[0] = layers[0].to(dev)
755
+
756
+ dtype = next(iter(model.parameters())).dtype
757
+ inps = torch.zeros(
758
+ (nsamples, model.seqlen, model.config.hidden_size), dtype=dtype, device=dev
759
+ )
760
+ cache = {"i": 0, "attention_mask": None}
761
+
762
+ class Catcher(nn.Module):
763
+ def __init__(self, module):
764
+ super().__init__()
765
+ self.module = module
766
+
767
+ def forward(self, inp, **kwargs):
768
+ inps[cache["i"]] = inp
769
+ cache["i"] += 1
770
+ cache["attention_mask"] = kwargs["attention_mask"]
771
+ raise ValueError
772
+
773
+ layers[0] = Catcher(layers[0])
774
+ for i in range(nsamples):
775
+ batch = testenc[:, (i * model.seqlen) : ((i + 1) * model.seqlen)].to(dev)
776
+ try:
777
+ model(batch)
778
+ except ValueError:
779
+ pass
780
+ layers[0] = layers[0].module
781
+
782
+ layers[0] = layers[0].cpu()
783
+ model.model.embed_tokens = model.model.embed_tokens.cpu()
784
+ torch.cuda.empty_cache()
785
+
786
+ outs = torch.zeros_like(inps)
787
+ attention_mask = cache["attention_mask"]
788
+
789
+ for i in range(len(layers)):
790
+ print(i)
791
+ layer = layers[i].to(dev)
792
+
793
+ if args.gmp:
794
+ subset = find_layers(layer)
795
+ for name in subset:
796
+ W = subset[name].weight.data
797
+ thresh = torch.sort(torch.abs(W.flatten()))[0][
798
+ int(W.numel() * args.sparsity)
799
+ ]
800
+ W.data[torch.abs(W.data) <= thresh] = 0
801
+
802
+ for j in range(nsamples):
803
+ outs[j] = layer(inps[j].unsqueeze(0), attention_mask=attention_mask)[0]
804
+ layers[i] = layer.cpu()
805
+ del layer
806
+ torch.cuda.empty_cache()
807
+ inps, outs = outs, inps
808
+
809
+ if model.model.norm is not None:
810
+ model.model.norm = model.model.norm.to(dev)
811
+ model.lm_head = model.lm_head.to(dev)
812
+
813
+ testenc = testenc.to(dev)
814
+ nlls = []
815
+ for i in range(nsamples):
816
+ hidden_states = inps[i].unsqueeze(0)
817
+ if model.model.norm is not None:
818
+ hidden_states = model.model.norm(hidden_states)
819
+ lm_logits = model.lm_head(hidden_states)
820
+ shift_logits = lm_logits[:, :-1, :].contiguous()
821
+ shift_labels = testenc[:, (i * model.seqlen) : ((i + 1) * model.seqlen)][:, 1:]
822
+ loss_fct = nn.CrossEntropyLoss()
823
+ loss = loss_fct(
824
+ shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1)
825
+ )
826
+ neg_log_likelihood = loss.float() * model.seqlen
827
+ nlls.append(neg_log_likelihood)
828
+ ppl = torch.exp(torch.stack(nlls).sum() / (nsamples * model.seqlen))
829
+ print(f"Perplexity: {ppl.item():3f}")
830
+
831
+ model.config.use_cache = use_cache
opt_main.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from model_utils import get_opt, opt_sparsellm, opt_eval
3
+ from datautils import get_loaders
4
+ import torch
5
+
6
+ def main():
7
+ parser = argparse.ArgumentParser()
8
+
9
+ # Arguments parsing
10
+ parser.add_argument('--model', type=str, default='facebook/opt-125m', help='OPT model to load; pass `facebook/opt-X`.')
11
+ parser.add_argument('--dataset', type=str, choices=['wikitext2', 'ptb', 'c4'], default='c4', help='Where to extract calibration data from.')
12
+ parser.add_argument('--seed', type=int, default=0, help='Seed for sampling the calibration data.')
13
+ parser.add_argument('--nsamples', type=int, default=64, help='Number of calibration data samples.')
14
+ parser.add_argument('--percdamp', type=float, default=.01, help='Percent of the average Hessian diagonal to use for dampening.')
15
+ parser.add_argument('--sparsity', type=float, default=0.7, help='Target sparsity')
16
+ parser.add_argument('--prunen', type=int, default=0, help='N for N:M pruning.')
17
+ parser.add_argument('--prunem', type=int, default=0, help='M for N:M pruning.')
18
+ parser.add_argument('--blocksize', type=int, default=128, help='Blocksize to use for adaptive mask selection.')
19
+ parser.add_argument('--gmp', action='store_true', help='Whether to run the GMP baseline.')
20
+ parser.add_argument('--wbits', type=int, default=16, help='Whether to quantize as well.')
21
+ parser.add_argument('--minlayer', type=int, default=-1, help='Prune all layers with id >= this.')
22
+ parser.add_argument('--maxlayer', type=int, default=1000, help='Prune all layers with id < this.')
23
+ parser.add_argument('--prune_only', type=str, default='', help='Prune only layers that contain this text.')
24
+ parser.add_argument('--invert', action='store_true', help='Invert subset.')
25
+ parser.add_argument('--save', type=str, default='', help='Path to saved model.')
26
+ parser.add_argument('--log_wandb', action='store_true', help='Whether to log to wandb.')
27
+
28
+ args = parser.parse_args()
29
+
30
+ model = get_opt(args)
31
+ model.eval()
32
+ dataloader, testloader = get_loaders(args.dataset, nsamples=args.nsamples, seed=args.seed, model=args.model, seqlen=model.seqlen)
33
+
34
+ if (args.sparsity or args.prunen) and not args.gmp:
35
+ opt_sparsellm(model, dataloader, torch.device('cuda'), args)
36
+
37
+ for dataset in ['wikitext2', 'ptb', 'c4']:
38
+ dataloader, testloader = get_loaders(dataset, seed=args.seed, model=args.model, seqlen=model.seqlen)
39
+ opt_eval(model, testloader, torch.device('cuda'), args, dataset)
40
+
41
+ if args.save:
42
+ model.save_pretrained(args.save)
43
+
44
+ if __name__ == '__main__':
45
+ main()
pruning_utils.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file will contain helper functions related to the pruning process, including any specialized pruning functions and the SparseGPT functionality.
2
+ # DISCLAIMER: The SparseGPT class is a modified version of the original SparseGPT class. The original SparseGPT class can be found in [SparseGPT: Massive Language Models Can Be Accurately Pruned in One-Shot].
3
+
4
+ import math
5
+ import time
6
+
7
+ import torch
8
+ import torch.nn as nn
9
+ import transformers
10
+
11
+ from quant import *
12
+
13
+ # turned this flag to be True
14
+ DEBUG = True
15
+
16
+ torch.backends.cuda.matmul.allow_tf32 = False
17
+ torch.backends.cudnn.allow_tf32 = False
18
+
19
+ def find_layers(module, layers=[nn.Conv2d, nn.Linear], name=''):
20
+ if type(module) in layers:
21
+ return {name: module}
22
+ res = {}
23
+ for name1, child in module.named_children():
24
+ res.update(find_layers(
25
+ child, layers=layers, name=name + '.' + name1 if name != '' else name1
26
+ ))
27
+ return res
28
+
29
+ class SparseGPT_OPT:
30
+
31
+ def __init__(self, layer):
32
+ self.layer = layer
33
+ self.dev = self.layer.weight.device
34
+ W = layer.weight.data.clone()
35
+ if isinstance(self.layer, nn.Conv2d):
36
+ W = W.flatten(1)
37
+ if isinstance(self.layer, transformers.Conv1D):
38
+ W = W.t()
39
+ self.rows = W.shape[0]
40
+ self.columns = W.shape[1]
41
+ self.H = torch.zeros((self.columns, self.columns), device=self.dev)
42
+ self.nsamples = 0
43
+ self.batch_inp = []
44
+ self.batch_out = []
45
+
46
+ def add_batch(self, inp, out, name, blocksize=1024):
47
+ if DEBUG:
48
+ self.inp1 = inp
49
+ self.out1 = out
50
+ if len(inp.shape) == 2:
51
+ inp = inp.unsqueeze(0)
52
+ ###### added code
53
+ if name == 'fc1' or name == 'fc2':
54
+ self.batch_inp.append(inp[0].clone().detach())
55
+ if len(out.shape) == 3:
56
+ out = out.squeeze(0)
57
+ self.batch_out.append(out.clone().detach())
58
+ ######
59
+ tmp = inp.shape[0]
60
+ if isinstance(self.layer, nn.Linear) or isinstance(self.layer, transformers.Conv1D):
61
+ if len(inp.shape) == 3:
62
+ inp = inp.reshape((-1, inp.shape[-1]))
63
+ inp = inp.t()
64
+ self.H *= self.nsamples / (self.nsamples + tmp)
65
+ self.nsamples += tmp
66
+ inp = math.sqrt(2 / self.nsamples) * inp.float()
67
+ self.H += inp.matmul(inp.t())
68
+
69
+ def fasterprune(
70
+ self, sparsity, prunen=0, prunem=0, blocksize=128, percdamp=.01
71
+ ):
72
+ W = self.layer.weight.data.clone()
73
+ if isinstance(self.layer, nn.Conv2d):
74
+ W = W.flatten(1)
75
+ if isinstance(self.layer, transformers.Conv1D):
76
+ W = W.t()
77
+ W = W.float()
78
+
79
+ if hasattr(self, 'quantizer'):
80
+ if not self.quantizer.ready():
81
+ self.quantizer.find_params(W, weight=True)
82
+
83
+ tick = time.time()
84
+
85
+ H = self.H
86
+ # del self.H
87
+ dead = torch.diag(H) == 0
88
+ H[dead, dead] = 1
89
+ W[:, dead] = 0
90
+
91
+ Losses = torch.zeros(self.rows, device=self.dev)
92
+
93
+ damp = percdamp * torch.mean(torch.diag(H))
94
+ diag = torch.arange(self.columns, device=self.dev)
95
+ H[diag, diag] += damp
96
+ H = torch.linalg.cholesky(H)
97
+ H = torch.cholesky_inverse(H)
98
+ H = torch.linalg.cholesky(H, upper=True)
99
+ Hinv = H
100
+
101
+ mask = None
102
+
103
+ for i1 in range(0, self.columns, blocksize):
104
+ i2 = min(i1 + blocksize, self.columns)
105
+ count = i2 - i1
106
+
107
+ W1 = W[:, i1:i2].clone()
108
+ Q1 = torch.zeros_like(W1)
109
+ Err1 = torch.zeros_like(W1)
110
+ Losses1 = torch.zeros_like(W1)
111
+ Hinv1 = Hinv[i1:i2, i1:i2]
112
+
113
+ if prunen == 0:
114
+ if mask is not None:
115
+ mask1 = mask[:, i1:i2]
116
+ else:
117
+ tmp = W1 ** 2 / (torch.diag(Hinv1).reshape((1, -1))) ** 2
118
+ thresh = torch.sort(tmp.flatten())[0][int(tmp.numel() * sparsity)]
119
+ mask1 = tmp <= thresh
120
+ else:
121
+ mask1 = torch.zeros_like(W1) == 1
122
+
123
+ for i in range(count):
124
+ w = W1[:, i]
125
+ d = Hinv1[i, i]
126
+
127
+ if prunen != 0 and i % prunem == 0:
128
+ tmp = W1[:, i:(i + prunem)] ** 2 / (torch.diag(Hinv1)[i:(i + prunem)].reshape((1, -1))) ** 2
129
+ mask1.scatter_(1, i + torch.topk(tmp, prunen, dim=1, largest=False)[1], True)
130
+
131
+ q = w.clone()
132
+ q[mask1[:, i]] = 0
133
+
134
+ if hasattr(self, 'quantizer'):
135
+ q = quantize(
136
+ q.unsqueeze(1), self.quantizer.scale, self.quantizer.zero, self.quantizer.maxq
137
+ ).flatten()
138
+
139
+ Q1[:, i] = q
140
+ Losses1[:, i] = (w - q) ** 2 / d ** 2
141
+
142
+ err1 = (w - q) / d
143
+ W1[:, i:] -= err1.unsqueeze(1).matmul(Hinv1[i, i:].unsqueeze(0))
144
+ Err1[:, i] = err1
145
+
146
+ W[:, i1:i2] = Q1
147
+ Losses += torch.sum(Losses1, 1) / 2
148
+
149
+ W[:, i2:] -= Err1.matmul(Hinv[i1:i2, i2:])
150
+
151
+ # if DEBUG:
152
+ # self.layer.weight.data[:, :i2] = W[:, :i2]
153
+ # self.layer.weight.data[:, i2:] = W[:, i2:]
154
+ # print(torch.sum((self.layer(self.inp1) - self.out1) ** 2))
155
+ # print(torch.sum(Losses))
156
+
157
+ torch.cuda.synchronize()
158
+ print('time %.2f' % (time.time() - tick))
159
+ print('error', torch.sum(Losses).item())
160
+
161
+ if isinstance(self.layer, transformers.Conv1D):
162
+ W = W.t()
163
+ self.layer.weight.data = W.reshape(self.layer.weight.shape).to(self.layer.weight.data.dtype)
164
+ # if DEBUG:
165
+ # print(torch.sum((self.layer(self.inp1) - self.out1) ** 2))
166
+
167
+ def free(self):
168
+ if DEBUG:
169
+ self.inp1 = None
170
+ self.out1 = None
171
+ self.H = None
172
+ torch.cuda.empty_cache()
173
+
174
+
175
+
176
+
177
+ class SparseGPT_LlaMA:
178
+
179
+ def __init__(self, layer):
180
+ self.layer = layer
181
+ self.dev = self.layer.weight.device
182
+ W = layer.weight.data.clone()
183
+ if isinstance(self.layer, nn.Conv2d):
184
+ W = W.flatten(1)
185
+ if isinstance(self.layer, transformers.Conv1D):
186
+ W = W.t()
187
+ self.rows = W.shape[0]
188
+ self.columns = W.shape[1]
189
+ self.H = torch.zeros((self.columns, self.columns), device=self.dev)
190
+ self.nsamples = 0
191
+ self.batch_inp = []
192
+ self.batch_out = []
193
+
194
+ def add_batch(self, inp, out, name, blocksize=1024):
195
+ if DEBUG:
196
+ self.inp1 = inp
197
+ self.out1 = out
198
+ if len(inp.shape) == 2:
199
+ inp = inp.unsqueeze(0)
200
+ ###### added code
201
+ if name == 'mlp.up_proj' or name == 'mlp.down_proj':
202
+ self.batch_inp.append(inp[0].clone().detach())
203
+ if len(out.shape) == 3:
204
+ out = out.squeeze(0)
205
+ self.batch_out.append(out.clone().detach())
206
+ if name == 'mlp.gate_proj': # for this layer, we only store the outputs. for inputs, they are shared with 'mlp.up_proj'
207
+ if len(out.shape) == 3:
208
+ out = out.squeeze(0)
209
+ self.batch_out.append(out.clone().detach())
210
+ ######
211
+ tmp = inp.shape[0]
212
+ if isinstance(self.layer, nn.Linear) or isinstance(self.layer, transformers.Conv1D):
213
+ if len(inp.shape) == 3:
214
+ inp = inp.reshape((-1, inp.shape[-1]))
215
+ inp = inp.t()
216
+ self.H *= self.nsamples / (self.nsamples + tmp)
217
+ self.nsamples += tmp
218
+ inp = math.sqrt(2 / self.nsamples) * inp.float()
219
+ self.H += inp.matmul(inp.t())
220
+
221
+ def fasterprune(
222
+ self, sparsity, prunen=0, prunem=0, blocksize=128, percdamp=.01
223
+ ):
224
+ W = self.layer.weight.data.clone()
225
+ if isinstance(self.layer, nn.Conv2d):
226
+ W = W.flatten(1)
227
+ if isinstance(self.layer, transformers.Conv1D):
228
+ W = W.t()
229
+ W = W.float()
230
+
231
+ if hasattr(self, 'quantizer'):
232
+ if not self.quantizer.ready():
233
+ self.quantizer.find_params(W, weight=True)
234
+
235
+ tick = time.time()
236
+
237
+ H = self.H
238
+ # del self.H
239
+ dead = torch.diag(H) == 0
240
+ H[dead, dead] = 1
241
+ W[:, dead] = 0
242
+
243
+ Losses = torch.zeros(self.rows, device=self.dev)
244
+
245
+ damp = percdamp * torch.mean(torch.diag(H))
246
+ diag = torch.arange(self.columns, device=self.dev)
247
+ H[diag, diag] += damp
248
+ H = torch.linalg.cholesky(H)
249
+ H = torch.cholesky_inverse(H)
250
+ H = torch.linalg.cholesky(H, upper=True)
251
+ Hinv = H
252
+
253
+ mask = None
254
+
255
+ for i1 in range(0, self.columns, blocksize):
256
+ i2 = min(i1 + blocksize, self.columns)
257
+ count = i2 - i1
258
+
259
+ W1 = W[:, i1:i2].clone()
260
+ Q1 = torch.zeros_like(W1)
261
+ Err1 = torch.zeros_like(W1)
262
+ Losses1 = torch.zeros_like(W1)
263
+ Hinv1 = Hinv[i1:i2, i1:i2]
264
+
265
+ if prunen == 0:
266
+ if mask is not None:
267
+ mask1 = mask[:, i1:i2]
268
+ else:
269
+ tmp = W1 ** 2 / (torch.diag(Hinv1).reshape((1, -1))) ** 2
270
+ thresh = torch.sort(tmp.flatten())[0][int(tmp.numel() * sparsity)]
271
+ mask1 = tmp <= thresh
272
+ else:
273
+ mask1 = torch.zeros_like(W1) == 1
274
+
275
+ for i in range(count):
276
+ w = W1[:, i]
277
+ d = Hinv1[i, i]
278
+
279
+ if prunen != 0 and i % prunem == 0:
280
+ tmp = W1[:, i:(i + prunem)] ** 2 / (torch.diag(Hinv1)[i:(i + prunem)].reshape((1, -1))) ** 2
281
+ mask1.scatter_(1, i + torch.topk(tmp, prunen, dim=1, largest=False)[1], True)
282
+
283
+ q = w.clone()
284
+ q[mask1[:, i]] = 0
285
+
286
+ if hasattr(self, 'quantizer'):
287
+ q = quantize(
288
+ q.unsqueeze(1), self.quantizer.scale, self.quantizer.zero, self.quantizer.maxq
289
+ ).flatten()
290
+
291
+ Q1[:, i] = q
292
+ Losses1[:, i] = (w - q) ** 2 / d ** 2
293
+
294
+ err1 = (w - q) / d
295
+ W1[:, i:] -= err1.unsqueeze(1).matmul(Hinv1[i, i:].unsqueeze(0))
296
+ Err1[:, i] = err1
297
+
298
+ W[:, i1:i2] = Q1
299
+ Losses += torch.sum(Losses1, 1) / 2
300
+
301
+ W[:, i2:] -= Err1.matmul(Hinv[i1:i2, i2:])
302
+
303
+ # if DEBUG:
304
+ # self.layer.weight.data[:, :i2] = W[:, :i2]
305
+ # self.layer.weight.data[:, i2:] = W[:, i2:]
306
+ # print(torch.sum((self.layer(self.inp1) - self.out1) ** 2))
307
+ # print(torch.sum(Losses))
308
+
309
+ torch.cuda.synchronize()
310
+ print('time %.2f' % (time.time() - tick))
311
+ print('error', torch.sum(Losses).item())
312
+
313
+ if isinstance(self.layer, transformers.Conv1D):
314
+ W = W.t()
315
+ self.layer.weight.data = W.reshape(self.layer.weight.shape).to(self.layer.weight.data.dtype)
316
+ # if DEBUG:
317
+ # print(torch.sum((self.layer(self.inp1) - self.out1) ** 2))
318
+
319
+ def free(self):
320
+ if DEBUG:
321
+ self.inp1 = None
322
+ self.out1 = None
323
+ self.H = None
324
+ torch.cuda.empty_cache()
quant.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ import torch.nn as nn
4
+
5
+
6
+ def quantize(x, scale, zero, maxq):
7
+ q = torch.clamp(torch.round(x / scale) + zero, 0, maxq)
8
+ return scale * (q - zero)
9
+
10
+ class Quantizer(nn.Module):
11
+
12
+ def __init__(self, shape=1):
13
+ super(Quantizer, self).__init__()
14
+ self.register_buffer('maxq', torch.tensor(0))
15
+ self.register_buffer('scale', torch.zeros(shape))
16
+ self.register_buffer('zero', torch.zeros(shape))
17
+
18
+ def configure(
19
+ self,
20
+ bits, perchannel=False, sym=True,
21
+ mse=False, norm=2.4, grid=100, maxshrink=.8,
22
+ grouprows=1
23
+ ):
24
+ self.maxq = torch.tensor(2 ** bits - 1)
25
+ self.perchannel = perchannel
26
+ self.sym = sym
27
+ self.mse = mse
28
+ self.norm = norm
29
+ self.grid = grid
30
+ self.maxshrink = maxshrink
31
+ self.grouprows = grouprows
32
+
33
+ def find_params(self, x, weight=False):
34
+ dev = x.device
35
+ self.maxq = self.maxq.to(dev)
36
+
37
+ shape = x.shape
38
+ if self.perchannel:
39
+ if weight:
40
+ x = x.flatten(1)
41
+ if self.grouprows > 1:
42
+ x = x.reshape((x.shape[0] // self.grouprows, -1))
43
+ else:
44
+ if len(shape) == 4:
45
+ x = x.permute([1, 0, 2, 3])
46
+ x = x.flatten(1)
47
+ if len(shape) == 3:
48
+ x = x.reshape((-1, shape[-1])).t()
49
+ if len(shape) == 2:
50
+ x = x.t()
51
+ else:
52
+ x = x.flatten().unsqueeze(0)
53
+
54
+ tmp = torch.zeros(x.shape[0], device=dev)
55
+ xmin = torch.minimum(x.min(1)[0], tmp)
56
+ xmax = torch.maximum(x.max(1)[0], tmp)
57
+
58
+ if self.sym:
59
+ xmax = torch.maximum(torch.abs(xmin), xmax)
60
+ tmp = xmin < 0
61
+ if torch.any(tmp):
62
+ xmin[tmp] = -xmax[tmp]
63
+ tmp = (xmin == 0) & (xmax == 0)
64
+ xmin[tmp] = -1
65
+ xmax[tmp] = +1
66
+
67
+ self.scale = (xmax - xmin) / self.maxq
68
+ if self.sym:
69
+ self.zero = torch.full_like(self.scale, (self.maxq + 1) / 2)
70
+ else:
71
+ self.zero = torch.round(-xmin / self.scale)
72
+
73
+ if self.mse:
74
+ best = torch.full([x.shape[0]], float('inf'), device=dev)
75
+ for i in range(int(self.maxshrink * self.grid)):
76
+ p = 1 - i / self.grid
77
+ xmin1 = p * xmin
78
+ xmax1 = p * xmax
79
+ scale1 = (xmax1 - xmin1) / self.maxq
80
+ zero1 = torch.round(-xmin1 / scale1) if not self.sym else self.zero
81
+ q = quantize(x, scale1.unsqueeze(1), zero1.unsqueeze(1), self.maxq)
82
+ q -= x
83
+ q.abs_()
84
+ q.pow_(self.norm)
85
+ err = torch.sum(q, 1)
86
+ tmp = err < best
87
+ if torch.any(tmp):
88
+ best[tmp] = err[tmp]
89
+ self.scale[tmp] = scale1[tmp]
90
+ self.zero[tmp] = zero1[tmp]
91
+ if not self.perchannel:
92
+ if weight:
93
+ tmp = shape[0]
94
+ else:
95
+ tmp = shape[1] if len(shape) != 3 else shape[2]
96
+ self.scale = self.scale.repeat(tmp)
97
+ self.zero = self.zero.repeat(tmp)
98
+
99
+ if weight:
100
+ if self.grouprows > 1:
101
+ self.scale = self.scale.unsqueeze(1).repeat(1, self.grouprows)
102
+ self.zero = self.zero.unsqueeze(1).repeat(1, self.grouprows)
103
+ shape = [-1] + [1] * (len(shape) - 1)
104
+ self.scale = self.scale.reshape(shape)
105
+ self.zero = self.zero.reshape(shape)
106
+ return
107
+ if len(shape) == 4:
108
+ self.scale = self.scale.reshape((1, -1, 1, 1))
109
+ self.zero = self.zero.reshape((1, -1, 1, 1))
110
+ if len(shape) == 3:
111
+ self.scale = self.scale.reshape((1, 1, -1))
112
+ self.zero = self.zero.reshape((1, 1, -1))
113
+ if len(shape) == 2:
114
+ self.scale = self.scale.unsqueeze(0)
115
+ self.zero = self.zero.unsqueeze(0)
116
+
117
+ def quantize(self, x):
118
+ if self.ready():
119
+ return quantize(x, self.scale, self.zero, self.maxq)
120
+ return x
121
+
122
+ def enabled(self):
123
+ return self.maxq > 0
124
+
125
+ def ready(self):
126
+ return torch.all(self.scale != 0)