KnutJaegersberg
commited on
Commit
•
c1a41d7
1
Parent(s):
0d7dade
Upload 132 files
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +10 -0
- added_tokens.json +4 -0
- config.json +40 -0
- generation_config.json +7 -0
- model-00001-of-00002.safetensors +3 -0
- model-00002-of-00002.safetensors +3 -0
- model.safetensors.index.json +0 -0
- quip-sharp/.gitignore +16 -0
- quip-sharp/LICENSE +674 -0
- quip-sharp/README.md +114 -0
- quip-sharp/docs/Makefile +2 -0
- quip-sharp/docs/img/kissing2d.png +0 -0
- quip-sharp/docs/img/lattice_err.png +0 -0
- quip-sharp/docs/img/overview.svg +0 -0
- quip-sharp/docs/index.html +835 -0
- quip-sharp/docs/index.md +254 -0
- quip-sharp/eval_ppl.py +67 -0
- quip-sharp/eval_zeroshot.py +60 -0
- quip-sharp/gen_speed.py +45 -0
- quip-sharp/hessian_offline_llama.py +256 -0
- quip-sharp/hfize_llama.py +177 -0
- quip-sharp/interactive_gen.py +46 -0
- quip-sharp/lib/__init__.py +1 -0
- quip-sharp/lib/__pycache__/__init__.cpython-310.pyc +0 -0
- quip-sharp/lib/__pycache__/__init__.cpython-39.pyc +0 -0
- quip-sharp/lib/algo/__init__.py +0 -0
- quip-sharp/lib/algo/__pycache__/__init__.cpython-39.pyc +0 -0
- quip-sharp/lib/algo/__pycache__/outlier_channel_split.cpython-39.pyc +0 -0
- quip-sharp/lib/algo/__pycache__/preprocess.cpython-39.pyc +0 -0
- quip-sharp/lib/algo/__pycache__/quip.cpython-39.pyc +0 -0
- quip-sharp/lib/algo/outlier_channel_split.py +41 -0
- quip-sharp/lib/algo/preprocess.py +10 -0
- quip-sharp/lib/algo/process.py +9 -0
- quip-sharp/lib/algo/quip.py +417 -0
- quip-sharp/lib/codebook/__init__.py +31 -0
- quip-sharp/lib/codebook/__pycache__/__init__.cpython-310.pyc +0 -0
- quip-sharp/lib/codebook/__pycache__/__init__.cpython-39.pyc +0 -0
- quip-sharp/lib/codebook/__pycache__/half_integer_4bit_1col.cpython-310.pyc +0 -0
- quip-sharp/lib/codebook/__pycache__/half_integer_4bit_1col.cpython-39.pyc +0 -0
- quip-sharp/lib/codebook/__pycache__/latticed4.cpython-310.pyc +0 -0
- quip-sharp/lib/codebook/__pycache__/latticed4.cpython-39.pyc +0 -0
- quip-sharp/lib/codebook/__pycache__/latticee8_padded12.cpython-310.pyc +0 -0
- quip-sharp/lib/codebook/__pycache__/latticee8_padded12.cpython-39.pyc +0 -0
- quip-sharp/lib/codebook/half_integer_4bit_1col.py +138 -0
- quip-sharp/lib/codebook/latticed4.py +220 -0
- quip-sharp/lib/codebook/latticee8_padded12.py +265 -0
- quip-sharp/lib/linear/__init__.py +0 -0
- quip-sharp/lib/linear/__pycache__/__init__.cpython-310.pyc +0 -0
- quip-sharp/lib/linear/__pycache__/__init__.cpython-39.pyc +0 -0
- quip-sharp/lib/linear/__pycache__/quantized_linear.cpython-310.pyc +0 -0
.gitattributes
CHANGED
@@ -33,3 +33,13 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
quip-sharp/quiptools/build/lib.linux-x86_64-cpython-310/quiptools_cuda.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
37 |
+
quip-sharp/quiptools/build/lib.linux-x86_64-cpython-39/quiptools_cuda.cpython-39-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
38 |
+
quip-sharp/quiptools/build/temp.linux-x86_64-cpython-310/quiptools_e8p_gemv.o filter=lfs diff=lfs merge=lfs -text
|
39 |
+
quip-sharp/quiptools/build/temp.linux-x86_64-cpython-310/quiptools_wrapper.o filter=lfs diff=lfs merge=lfs -text
|
40 |
+
quip-sharp/quiptools/build/temp.linux-x86_64-cpython-310/quiptools.o filter=lfs diff=lfs merge=lfs -text
|
41 |
+
quip-sharp/quiptools/build/temp.linux-x86_64-cpython-39/quiptools_e8p_gemv.o filter=lfs diff=lfs merge=lfs -text
|
42 |
+
quip-sharp/quiptools/build/temp.linux-x86_64-cpython-39/quiptools_wrapper.o filter=lfs diff=lfs merge=lfs -text
|
43 |
+
quip-sharp/quiptools/build/temp.linux-x86_64-cpython-39/quiptools.o filter=lfs diff=lfs merge=lfs -text
|
44 |
+
quip-sharp/quiptools/dist/quiptools_cuda-0.0.0-py3.10-linux-x86_64.egg filter=lfs diff=lfs merge=lfs -text
|
45 |
+
quip-sharp/quiptools/dist/quiptools_cuda-0.0.0-py3.9-linux-x86_64.egg filter=lfs diff=lfs merge=lfs -text
|
added_tokens.json
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"</s>": 64001,
|
3 |
+
"<s>": 64000
|
4 |
+
}
|
config.json
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "/run/media/knut/HD2/LLMs2/40b/fine-tuned/Tess-34B-v1.4",
|
3 |
+
"architectures": [
|
4 |
+
"LlamaForCausalLM"
|
5 |
+
],
|
6 |
+
"attention_bias": false,
|
7 |
+
"bos_token_id": 64000,
|
8 |
+
"eos_token_id": 64001,
|
9 |
+
"hidden_act": "silu",
|
10 |
+
"hidden_size": 7168,
|
11 |
+
"initializer_range": 0.02,
|
12 |
+
"intermediate_size": 20480,
|
13 |
+
"max_position_embeddings": 200000,
|
14 |
+
"model_type": "llama",
|
15 |
+
"num_attention_heads": 56,
|
16 |
+
"num_hidden_layers": 60,
|
17 |
+
"num_key_value_heads": 8,
|
18 |
+
"pad_token_id": 0,
|
19 |
+
"pretraining_tp": 1,
|
20 |
+
"quip_params": {
|
21 |
+
"codebook": "E8P12",
|
22 |
+
"codebook_version": 0,
|
23 |
+
"codesz": 8,
|
24 |
+
"fused": true,
|
25 |
+
"idx_dtype": "torch.int16",
|
26 |
+
"lora_rank": 0,
|
27 |
+
"model_version": 0,
|
28 |
+
"outlier_channel_split": false,
|
29 |
+
"packsz": 1,
|
30 |
+
"rescale_WH": false
|
31 |
+
},
|
32 |
+
"rms_norm_eps": 1e-05,
|
33 |
+
"rope_scaling": null,
|
34 |
+
"rope_theta": 5000000.0,
|
35 |
+
"tie_word_embeddings": false,
|
36 |
+
"torch_dtype": "float16",
|
37 |
+
"transformers_version": "4.34.0",
|
38 |
+
"use_cache": false,
|
39 |
+
"vocab_size": 64002
|
40 |
+
}
|
generation_config.json
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"bos_token_id": 1,
|
4 |
+
"eos_token_id": 2,
|
5 |
+
"pad_token_id": 0,
|
6 |
+
"transformers_version": "4.34.0"
|
7 |
+
}
|
model-00001-of-00002.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:3accaaf5f23e119a17a279dd360f7b77b420ff8ac831bfeb4a6b8939621ba99e
|
3 |
+
size 9299868984
|
model-00002-of-00002.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9fca7572b3f9c2455b621458eecd4a109d5733b40954e89283637203bf15089e
|
3 |
+
size 917532800
|
model.safetensors.index.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
quip-sharp/.gitignore
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
*.pt
|
2 |
+
*~
|
3 |
+
*.safetensors
|
4 |
+
*.err
|
5 |
+
*.out
|
6 |
+
*.json
|
7 |
+
__pycache__/
|
8 |
+
#*
|
9 |
+
slurm_out/
|
10 |
+
hfized/
|
11 |
+
quiptools/build/
|
12 |
+
quiptools/dist
|
13 |
+
hadamard_cuda/build/
|
14 |
+
hadamard_cuda/dist/
|
15 |
+
report*.nsys-rep
|
16 |
+
report*.sqlite
|
quip-sharp/LICENSE
ADDED
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
GNU GENERAL PUBLIC LICENSE
|
2 |
+
Version 3, 29 June 2007
|
3 |
+
|
4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
6 |
+
of this license document, but changing it is not allowed.
|
7 |
+
|
8 |
+
Preamble
|
9 |
+
|
10 |
+
The GNU General Public License is a free, copyleft license for
|
11 |
+
software and other kinds of works.
|
12 |
+
|
13 |
+
The licenses for most software and other practical works are designed
|
14 |
+
to take away your freedom to share and change the works. By contrast,
|
15 |
+
the GNU General Public License is intended to guarantee your freedom to
|
16 |
+
share and change all versions of a program--to make sure it remains free
|
17 |
+
software for all its users. We, the Free Software Foundation, use the
|
18 |
+
GNU General Public License for most of our software; it applies also to
|
19 |
+
any other work released this way by its authors. You can apply it to
|
20 |
+
your programs, too.
|
21 |
+
|
22 |
+
When we speak of free software, we are referring to freedom, not
|
23 |
+
price. Our General Public Licenses are designed to make sure that you
|
24 |
+
have the freedom to distribute copies of free software (and charge for
|
25 |
+
them if you wish), that you receive source code or can get it if you
|
26 |
+
want it, that you can change the software or use pieces of it in new
|
27 |
+
free programs, and that you know you can do these things.
|
28 |
+
|
29 |
+
To protect your rights, we need to prevent others from denying you
|
30 |
+
these rights or asking you to surrender the rights. Therefore, you have
|
31 |
+
certain responsibilities if you distribute copies of the software, or if
|
32 |
+
you modify it: responsibilities to respect the freedom of others.
|
33 |
+
|
34 |
+
For example, if you distribute copies of such a program, whether
|
35 |
+
gratis or for a fee, you must pass on to the recipients the same
|
36 |
+
freedoms that you received. You must make sure that they, too, receive
|
37 |
+
or can get the source code. And you must show them these terms so they
|
38 |
+
know their rights.
|
39 |
+
|
40 |
+
Developers that use the GNU GPL protect your rights with two steps:
|
41 |
+
(1) assert copyright on the software, and (2) offer you this License
|
42 |
+
giving you legal permission to copy, distribute and/or modify it.
|
43 |
+
|
44 |
+
For the developers' and authors' protection, the GPL clearly explains
|
45 |
+
that there is no warranty for this free software. For both users' and
|
46 |
+
authors' sake, the GPL requires that modified versions be marked as
|
47 |
+
changed, so that their problems will not be attributed erroneously to
|
48 |
+
authors of previous versions.
|
49 |
+
|
50 |
+
Some devices are designed to deny users access to install or run
|
51 |
+
modified versions of the software inside them, although the manufacturer
|
52 |
+
can do so. This is fundamentally incompatible with the aim of
|
53 |
+
protecting users' freedom to change the software. The systematic
|
54 |
+
pattern of such abuse occurs in the area of products for individuals to
|
55 |
+
use, which is precisely where it is most unacceptable. Therefore, we
|
56 |
+
have designed this version of the GPL to prohibit the practice for those
|
57 |
+
products. If such problems arise substantially in other domains, we
|
58 |
+
stand ready to extend this provision to those domains in future versions
|
59 |
+
of the GPL, as needed to protect the freedom of users.
|
60 |
+
|
61 |
+
Finally, every program is threatened constantly by software patents.
|
62 |
+
States should not allow patents to restrict development and use of
|
63 |
+
software on general-purpose computers, but in those that do, we wish to
|
64 |
+
avoid the special danger that patents applied to a free program could
|
65 |
+
make it effectively proprietary. To prevent this, the GPL assures that
|
66 |
+
patents cannot be used to render the program non-free.
|
67 |
+
|
68 |
+
The precise terms and conditions for copying, distribution and
|
69 |
+
modification follow.
|
70 |
+
|
71 |
+
TERMS AND CONDITIONS
|
72 |
+
|
73 |
+
0. Definitions.
|
74 |
+
|
75 |
+
"This License" refers to version 3 of the GNU General Public License.
|
76 |
+
|
77 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
78 |
+
works, such as semiconductor masks.
|
79 |
+
|
80 |
+
"The Program" refers to any copyrightable work licensed under this
|
81 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
82 |
+
"recipients" may be individuals or organizations.
|
83 |
+
|
84 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
85 |
+
in a fashion requiring copyright permission, other than the making of an
|
86 |
+
exact copy. The resulting work is called a "modified version" of the
|
87 |
+
earlier work or a work "based on" the earlier work.
|
88 |
+
|
89 |
+
A "covered work" means either the unmodified Program or a work based
|
90 |
+
on the Program.
|
91 |
+
|
92 |
+
To "propagate" a work means to do anything with it that, without
|
93 |
+
permission, would make you directly or secondarily liable for
|
94 |
+
infringement under applicable copyright law, except executing it on a
|
95 |
+
computer or modifying a private copy. Propagation includes copying,
|
96 |
+
distribution (with or without modification), making available to the
|
97 |
+
public, and in some countries other activities as well.
|
98 |
+
|
99 |
+
To "convey" a work means any kind of propagation that enables other
|
100 |
+
parties to make or receive copies. Mere interaction with a user through
|
101 |
+
a computer network, with no transfer of a copy, is not conveying.
|
102 |
+
|
103 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
104 |
+
to the extent that it includes a convenient and prominently visible
|
105 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
106 |
+
tells the user that there is no warranty for the work (except to the
|
107 |
+
extent that warranties are provided), that licensees may convey the
|
108 |
+
work under this License, and how to view a copy of this License. If
|
109 |
+
the interface presents a list of user commands or options, such as a
|
110 |
+
menu, a prominent item in the list meets this criterion.
|
111 |
+
|
112 |
+
1. Source Code.
|
113 |
+
|
114 |
+
The "source code" for a work means the preferred form of the work
|
115 |
+
for making modifications to it. "Object code" means any non-source
|
116 |
+
form of a work.
|
117 |
+
|
118 |
+
A "Standard Interface" means an interface that either is an official
|
119 |
+
standard defined by a recognized standards body, or, in the case of
|
120 |
+
interfaces specified for a particular programming language, one that
|
121 |
+
is widely used among developers working in that language.
|
122 |
+
|
123 |
+
The "System Libraries" of an executable work include anything, other
|
124 |
+
than the work as a whole, that (a) is included in the normal form of
|
125 |
+
packaging a Major Component, but which is not part of that Major
|
126 |
+
Component, and (b) serves only to enable use of the work with that
|
127 |
+
Major Component, or to implement a Standard Interface for which an
|
128 |
+
implementation is available to the public in source code form. A
|
129 |
+
"Major Component", in this context, means a major essential component
|
130 |
+
(kernel, window system, and so on) of the specific operating system
|
131 |
+
(if any) on which the executable work runs, or a compiler used to
|
132 |
+
produce the work, or an object code interpreter used to run it.
|
133 |
+
|
134 |
+
The "Corresponding Source" for a work in object code form means all
|
135 |
+
the source code needed to generate, install, and (for an executable
|
136 |
+
work) run the object code and to modify the work, including scripts to
|
137 |
+
control those activities. However, it does not include the work's
|
138 |
+
System Libraries, or general-purpose tools or generally available free
|
139 |
+
programs which are used unmodified in performing those activities but
|
140 |
+
which are not part of the work. For example, Corresponding Source
|
141 |
+
includes interface definition files associated with source files for
|
142 |
+
the work, and the source code for shared libraries and dynamically
|
143 |
+
linked subprograms that the work is specifically designed to require,
|
144 |
+
such as by intimate data communication or control flow between those
|
145 |
+
subprograms and other parts of the work.
|
146 |
+
|
147 |
+
The Corresponding Source need not include anything that users
|
148 |
+
can regenerate automatically from other parts of the Corresponding
|
149 |
+
Source.
|
150 |
+
|
151 |
+
The Corresponding Source for a work in source code form is that
|
152 |
+
same work.
|
153 |
+
|
154 |
+
2. Basic Permissions.
|
155 |
+
|
156 |
+
All rights granted under this License are granted for the term of
|
157 |
+
copyright on the Program, and are irrevocable provided the stated
|
158 |
+
conditions are met. This License explicitly affirms your unlimited
|
159 |
+
permission to run the unmodified Program. The output from running a
|
160 |
+
covered work is covered by this License only if the output, given its
|
161 |
+
content, constitutes a covered work. This License acknowledges your
|
162 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
163 |
+
|
164 |
+
You may make, run and propagate covered works that you do not
|
165 |
+
convey, without conditions so long as your license otherwise remains
|
166 |
+
in force. You may convey covered works to others for the sole purpose
|
167 |
+
of having them make modifications exclusively for you, or provide you
|
168 |
+
with facilities for running those works, provided that you comply with
|
169 |
+
the terms of this License in conveying all material for which you do
|
170 |
+
not control copyright. Those thus making or running the covered works
|
171 |
+
for you must do so exclusively on your behalf, under your direction
|
172 |
+
and control, on terms that prohibit them from making any copies of
|
173 |
+
your copyrighted material outside their relationship with you.
|
174 |
+
|
175 |
+
Conveying under any other circumstances is permitted solely under
|
176 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
177 |
+
makes it unnecessary.
|
178 |
+
|
179 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
180 |
+
|
181 |
+
No covered work shall be deemed part of an effective technological
|
182 |
+
measure under any applicable law fulfilling obligations under article
|
183 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
184 |
+
similar laws prohibiting or restricting circumvention of such
|
185 |
+
measures.
|
186 |
+
|
187 |
+
When you convey a covered work, you waive any legal power to forbid
|
188 |
+
circumvention of technological measures to the extent such circumvention
|
189 |
+
is effected by exercising rights under this License with respect to
|
190 |
+
the covered work, and you disclaim any intention to limit operation or
|
191 |
+
modification of the work as a means of enforcing, against the work's
|
192 |
+
users, your or third parties' legal rights to forbid circumvention of
|
193 |
+
technological measures.
|
194 |
+
|
195 |
+
4. Conveying Verbatim Copies.
|
196 |
+
|
197 |
+
You may convey verbatim copies of the Program's source code as you
|
198 |
+
receive it, in any medium, provided that you conspicuously and
|
199 |
+
appropriately publish on each copy an appropriate copyright notice;
|
200 |
+
keep intact all notices stating that this License and any
|
201 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
202 |
+
keep intact all notices of the absence of any warranty; and give all
|
203 |
+
recipients a copy of this License along with the Program.
|
204 |
+
|
205 |
+
You may charge any price or no price for each copy that you convey,
|
206 |
+
and you may offer support or warranty protection for a fee.
|
207 |
+
|
208 |
+
5. Conveying Modified Source Versions.
|
209 |
+
|
210 |
+
You may convey a work based on the Program, or the modifications to
|
211 |
+
produce it from the Program, in the form of source code under the
|
212 |
+
terms of section 4, provided that you also meet all of these conditions:
|
213 |
+
|
214 |
+
a) The work must carry prominent notices stating that you modified
|
215 |
+
it, and giving a relevant date.
|
216 |
+
|
217 |
+
b) The work must carry prominent notices stating that it is
|
218 |
+
released under this License and any conditions added under section
|
219 |
+
7. This requirement modifies the requirement in section 4 to
|
220 |
+
"keep intact all notices".
|
221 |
+
|
222 |
+
c) You must license the entire work, as a whole, under this
|
223 |
+
License to anyone who comes into possession of a copy. This
|
224 |
+
License will therefore apply, along with any applicable section 7
|
225 |
+
additional terms, to the whole of the work, and all its parts,
|
226 |
+
regardless of how they are packaged. This License gives no
|
227 |
+
permission to license the work in any other way, but it does not
|
228 |
+
invalidate such permission if you have separately received it.
|
229 |
+
|
230 |
+
d) If the work has interactive user interfaces, each must display
|
231 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
232 |
+
interfaces that do not display Appropriate Legal Notices, your
|
233 |
+
work need not make them do so.
|
234 |
+
|
235 |
+
A compilation of a covered work with other separate and independent
|
236 |
+
works, which are not by their nature extensions of the covered work,
|
237 |
+
and which are not combined with it such as to form a larger program,
|
238 |
+
in or on a volume of a storage or distribution medium, is called an
|
239 |
+
"aggregate" if the compilation and its resulting copyright are not
|
240 |
+
used to limit the access or legal rights of the compilation's users
|
241 |
+
beyond what the individual works permit. Inclusion of a covered work
|
242 |
+
in an aggregate does not cause this License to apply to the other
|
243 |
+
parts of the aggregate.
|
244 |
+
|
245 |
+
6. Conveying Non-Source Forms.
|
246 |
+
|
247 |
+
You may convey a covered work in object code form under the terms
|
248 |
+
of sections 4 and 5, provided that you also convey the
|
249 |
+
machine-readable Corresponding Source under the terms of this License,
|
250 |
+
in one of these ways:
|
251 |
+
|
252 |
+
a) Convey the object code in, or embodied in, a physical product
|
253 |
+
(including a physical distribution medium), accompanied by the
|
254 |
+
Corresponding Source fixed on a durable physical medium
|
255 |
+
customarily used for software interchange.
|
256 |
+
|
257 |
+
b) Convey the object code in, or embodied in, a physical product
|
258 |
+
(including a physical distribution medium), accompanied by a
|
259 |
+
written offer, valid for at least three years and valid for as
|
260 |
+
long as you offer spare parts or customer support for that product
|
261 |
+
model, to give anyone who possesses the object code either (1) a
|
262 |
+
copy of the Corresponding Source for all the software in the
|
263 |
+
product that is covered by this License, on a durable physical
|
264 |
+
medium customarily used for software interchange, for a price no
|
265 |
+
more than your reasonable cost of physically performing this
|
266 |
+
conveying of source, or (2) access to copy the
|
267 |
+
Corresponding Source from a network server at no charge.
|
268 |
+
|
269 |
+
c) Convey individual copies of the object code with a copy of the
|
270 |
+
written offer to provide the Corresponding Source. This
|
271 |
+
alternative is allowed only occasionally and noncommercially, and
|
272 |
+
only if you received the object code with such an offer, in accord
|
273 |
+
with subsection 6b.
|
274 |
+
|
275 |
+
d) Convey the object code by offering access from a designated
|
276 |
+
place (gratis or for a charge), and offer equivalent access to the
|
277 |
+
Corresponding Source in the same way through the same place at no
|
278 |
+
further charge. You need not require recipients to copy the
|
279 |
+
Corresponding Source along with the object code. If the place to
|
280 |
+
copy the object code is a network server, the Corresponding Source
|
281 |
+
may be on a different server (operated by you or a third party)
|
282 |
+
that supports equivalent copying facilities, provided you maintain
|
283 |
+
clear directions next to the object code saying where to find the
|
284 |
+
Corresponding Source. Regardless of what server hosts the
|
285 |
+
Corresponding Source, you remain obligated to ensure that it is
|
286 |
+
available for as long as needed to satisfy these requirements.
|
287 |
+
|
288 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
289 |
+
you inform other peers where the object code and Corresponding
|
290 |
+
Source of the work are being offered to the general public at no
|
291 |
+
charge under subsection 6d.
|
292 |
+
|
293 |
+
A separable portion of the object code, whose source code is excluded
|
294 |
+
from the Corresponding Source as a System Library, need not be
|
295 |
+
included in conveying the object code work.
|
296 |
+
|
297 |
+
A "User Product" is either (1) a "consumer product", which means any
|
298 |
+
tangible personal property which is normally used for personal, family,
|
299 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
300 |
+
into a dwelling. In determining whether a product is a consumer product,
|
301 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
302 |
+
product received by a particular user, "normally used" refers to a
|
303 |
+
typical or common use of that class of product, regardless of the status
|
304 |
+
of the particular user or of the way in which the particular user
|
305 |
+
actually uses, or expects or is expected to use, the product. A product
|
306 |
+
is a consumer product regardless of whether the product has substantial
|
307 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
308 |
+
the only significant mode of use of the product.
|
309 |
+
|
310 |
+
"Installation Information" for a User Product means any methods,
|
311 |
+
procedures, authorization keys, or other information required to install
|
312 |
+
and execute modified versions of a covered work in that User Product from
|
313 |
+
a modified version of its Corresponding Source. The information must
|
314 |
+
suffice to ensure that the continued functioning of the modified object
|
315 |
+
code is in no case prevented or interfered with solely because
|
316 |
+
modification has been made.
|
317 |
+
|
318 |
+
If you convey an object code work under this section in, or with, or
|
319 |
+
specifically for use in, a User Product, and the conveying occurs as
|
320 |
+
part of a transaction in which the right of possession and use of the
|
321 |
+
User Product is transferred to the recipient in perpetuity or for a
|
322 |
+
fixed term (regardless of how the transaction is characterized), the
|
323 |
+
Corresponding Source conveyed under this section must be accompanied
|
324 |
+
by the Installation Information. But this requirement does not apply
|
325 |
+
if neither you nor any third party retains the ability to install
|
326 |
+
modified object code on the User Product (for example, the work has
|
327 |
+
been installed in ROM).
|
328 |
+
|
329 |
+
The requirement to provide Installation Information does not include a
|
330 |
+
requirement to continue to provide support service, warranty, or updates
|
331 |
+
for a work that has been modified or installed by the recipient, or for
|
332 |
+
the User Product in which it has been modified or installed. Access to a
|
333 |
+
network may be denied when the modification itself materially and
|
334 |
+
adversely affects the operation of the network or violates the rules and
|
335 |
+
protocols for communication across the network.
|
336 |
+
|
337 |
+
Corresponding Source conveyed, and Installation Information provided,
|
338 |
+
in accord with this section must be in a format that is publicly
|
339 |
+
documented (and with an implementation available to the public in
|
340 |
+
source code form), and must require no special password or key for
|
341 |
+
unpacking, reading or copying.
|
342 |
+
|
343 |
+
7. Additional Terms.
|
344 |
+
|
345 |
+
"Additional permissions" are terms that supplement the terms of this
|
346 |
+
License by making exceptions from one or more of its conditions.
|
347 |
+
Additional permissions that are applicable to the entire Program shall
|
348 |
+
be treated as though they were included in this License, to the extent
|
349 |
+
that they are valid under applicable law. If additional permissions
|
350 |
+
apply only to part of the Program, that part may be used separately
|
351 |
+
under those permissions, but the entire Program remains governed by
|
352 |
+
this License without regard to the additional permissions.
|
353 |
+
|
354 |
+
When you convey a copy of a covered work, you may at your option
|
355 |
+
remove any additional permissions from that copy, or from any part of
|
356 |
+
it. (Additional permissions may be written to require their own
|
357 |
+
removal in certain cases when you modify the work.) You may place
|
358 |
+
additional permissions on material, added by you to a covered work,
|
359 |
+
for which you have or can give appropriate copyright permission.
|
360 |
+
|
361 |
+
Notwithstanding any other provision of this License, for material you
|
362 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
363 |
+
that material) supplement the terms of this License with terms:
|
364 |
+
|
365 |
+
a) Disclaiming warranty or limiting liability differently from the
|
366 |
+
terms of sections 15 and 16 of this License; or
|
367 |
+
|
368 |
+
b) Requiring preservation of specified reasonable legal notices or
|
369 |
+
author attributions in that material or in the Appropriate Legal
|
370 |
+
Notices displayed by works containing it; or
|
371 |
+
|
372 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
373 |
+
requiring that modified versions of such material be marked in
|
374 |
+
reasonable ways as different from the original version; or
|
375 |
+
|
376 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
377 |
+
authors of the material; or
|
378 |
+
|
379 |
+
e) Declining to grant rights under trademark law for use of some
|
380 |
+
trade names, trademarks, or service marks; or
|
381 |
+
|
382 |
+
f) Requiring indemnification of licensors and authors of that
|
383 |
+
material by anyone who conveys the material (or modified versions of
|
384 |
+
it) with contractual assumptions of liability to the recipient, for
|
385 |
+
any liability that these contractual assumptions directly impose on
|
386 |
+
those licensors and authors.
|
387 |
+
|
388 |
+
All other non-permissive additional terms are considered "further
|
389 |
+
restrictions" within the meaning of section 10. If the Program as you
|
390 |
+
received it, or any part of it, contains a notice stating that it is
|
391 |
+
governed by this License along with a term that is a further
|
392 |
+
restriction, you may remove that term. If a license document contains
|
393 |
+
a further restriction but permits relicensing or conveying under this
|
394 |
+
License, you may add to a covered work material governed by the terms
|
395 |
+
of that license document, provided that the further restriction does
|
396 |
+
not survive such relicensing or conveying.
|
397 |
+
|
398 |
+
If you add terms to a covered work in accord with this section, you
|
399 |
+
must place, in the relevant source files, a statement of the
|
400 |
+
additional terms that apply to those files, or a notice indicating
|
401 |
+
where to find the applicable terms.
|
402 |
+
|
403 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
404 |
+
form of a separately written license, or stated as exceptions;
|
405 |
+
the above requirements apply either way.
|
406 |
+
|
407 |
+
8. Termination.
|
408 |
+
|
409 |
+
You may not propagate or modify a covered work except as expressly
|
410 |
+
provided under this License. Any attempt otherwise to propagate or
|
411 |
+
modify it is void, and will automatically terminate your rights under
|
412 |
+
this License (including any patent licenses granted under the third
|
413 |
+
paragraph of section 11).
|
414 |
+
|
415 |
+
However, if you cease all violation of this License, then your
|
416 |
+
license from a particular copyright holder is reinstated (a)
|
417 |
+
provisionally, unless and until the copyright holder explicitly and
|
418 |
+
finally terminates your license, and (b) permanently, if the copyright
|
419 |
+
holder fails to notify you of the violation by some reasonable means
|
420 |
+
prior to 60 days after the cessation.
|
421 |
+
|
422 |
+
Moreover, your license from a particular copyright holder is
|
423 |
+
reinstated permanently if the copyright holder notifies you of the
|
424 |
+
violation by some reasonable means, this is the first time you have
|
425 |
+
received notice of violation of this License (for any work) from that
|
426 |
+
copyright holder, and you cure the violation prior to 30 days after
|
427 |
+
your receipt of the notice.
|
428 |
+
|
429 |
+
Termination of your rights under this section does not terminate the
|
430 |
+
licenses of parties who have received copies or rights from you under
|
431 |
+
this License. If your rights have been terminated and not permanently
|
432 |
+
reinstated, you do not qualify to receive new licenses for the same
|
433 |
+
material under section 10.
|
434 |
+
|
435 |
+
9. Acceptance Not Required for Having Copies.
|
436 |
+
|
437 |
+
You are not required to accept this License in order to receive or
|
438 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
439 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
440 |
+
to receive a copy likewise does not require acceptance. However,
|
441 |
+
nothing other than this License grants you permission to propagate or
|
442 |
+
modify any covered work. These actions infringe copyright if you do
|
443 |
+
not accept this License. Therefore, by modifying or propagating a
|
444 |
+
covered work, you indicate your acceptance of this License to do so.
|
445 |
+
|
446 |
+
10. Automatic Licensing of Downstream Recipients.
|
447 |
+
|
448 |
+
Each time you convey a covered work, the recipient automatically
|
449 |
+
receives a license from the original licensors, to run, modify and
|
450 |
+
propagate that work, subject to this License. You are not responsible
|
451 |
+
for enforcing compliance by third parties with this License.
|
452 |
+
|
453 |
+
An "entity transaction" is a transaction transferring control of an
|
454 |
+
organization, or substantially all assets of one, or subdividing an
|
455 |
+
organization, or merging organizations. If propagation of a covered
|
456 |
+
work results from an entity transaction, each party to that
|
457 |
+
transaction who receives a copy of the work also receives whatever
|
458 |
+
licenses to the work the party's predecessor in interest had or could
|
459 |
+
give under the previous paragraph, plus a right to possession of the
|
460 |
+
Corresponding Source of the work from the predecessor in interest, if
|
461 |
+
the predecessor has it or can get it with reasonable efforts.
|
462 |
+
|
463 |
+
You may not impose any further restrictions on the exercise of the
|
464 |
+
rights granted or affirmed under this License. For example, you may
|
465 |
+
not impose a license fee, royalty, or other charge for exercise of
|
466 |
+
rights granted under this License, and you may not initiate litigation
|
467 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
468 |
+
any patent claim is infringed by making, using, selling, offering for
|
469 |
+
sale, or importing the Program or any portion of it.
|
470 |
+
|
471 |
+
11. Patents.
|
472 |
+
|
473 |
+
A "contributor" is a copyright holder who authorizes use under this
|
474 |
+
License of the Program or a work on which the Program is based. The
|
475 |
+
work thus licensed is called the contributor's "contributor version".
|
476 |
+
|
477 |
+
A contributor's "essential patent claims" are all patent claims
|
478 |
+
owned or controlled by the contributor, whether already acquired or
|
479 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
480 |
+
by this License, of making, using, or selling its contributor version,
|
481 |
+
but do not include claims that would be infringed only as a
|
482 |
+
consequence of further modification of the contributor version. For
|
483 |
+
purposes of this definition, "control" includes the right to grant
|
484 |
+
patent sublicenses in a manner consistent with the requirements of
|
485 |
+
this License.
|
486 |
+
|
487 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
488 |
+
patent license under the contributor's essential patent claims, to
|
489 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
490 |
+
propagate the contents of its contributor version.
|
491 |
+
|
492 |
+
In the following three paragraphs, a "patent license" is any express
|
493 |
+
agreement or commitment, however denominated, not to enforce a patent
|
494 |
+
(such as an express permission to practice a patent or covenant not to
|
495 |
+
sue for patent infringement). To "grant" such a patent license to a
|
496 |
+
party means to make such an agreement or commitment not to enforce a
|
497 |
+
patent against the party.
|
498 |
+
|
499 |
+
If you convey a covered work, knowingly relying on a patent license,
|
500 |
+
and the Corresponding Source of the work is not available for anyone
|
501 |
+
to copy, free of charge and under the terms of this License, through a
|
502 |
+
publicly available network server or other readily accessible means,
|
503 |
+
then you must either (1) cause the Corresponding Source to be so
|
504 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
505 |
+
patent license for this particular work, or (3) arrange, in a manner
|
506 |
+
consistent with the requirements of this License, to extend the patent
|
507 |
+
license to downstream recipients. "Knowingly relying" means you have
|
508 |
+
actual knowledge that, but for the patent license, your conveying the
|
509 |
+
covered work in a country, or your recipient's use of the covered work
|
510 |
+
in a country, would infringe one or more identifiable patents in that
|
511 |
+
country that you have reason to believe are valid.
|
512 |
+
|
513 |
+
If, pursuant to or in connection with a single transaction or
|
514 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
515 |
+
covered work, and grant a patent license to some of the parties
|
516 |
+
receiving the covered work authorizing them to use, propagate, modify
|
517 |
+
or convey a specific copy of the covered work, then the patent license
|
518 |
+
you grant is automatically extended to all recipients of the covered
|
519 |
+
work and works based on it.
|
520 |
+
|
521 |
+
A patent license is "discriminatory" if it does not include within
|
522 |
+
the scope of its coverage, prohibits the exercise of, or is
|
523 |
+
conditioned on the non-exercise of one or more of the rights that are
|
524 |
+
specifically granted under this License. You may not convey a covered
|
525 |
+
work if you are a party to an arrangement with a third party that is
|
526 |
+
in the business of distributing software, under which you make payment
|
527 |
+
to the third party based on the extent of your activity of conveying
|
528 |
+
the work, and under which the third party grants, to any of the
|
529 |
+
parties who would receive the covered work from you, a discriminatory
|
530 |
+
patent license (a) in connection with copies of the covered work
|
531 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
532 |
+
for and in connection with specific products or compilations that
|
533 |
+
contain the covered work, unless you entered into that arrangement,
|
534 |
+
or that patent license was granted, prior to 28 March 2007.
|
535 |
+
|
536 |
+
Nothing in this License shall be construed as excluding or limiting
|
537 |
+
any implied license or other defenses to infringement that may
|
538 |
+
otherwise be available to you under applicable patent law.
|
539 |
+
|
540 |
+
12. No Surrender of Others' Freedom.
|
541 |
+
|
542 |
+
If conditions are imposed on you (whether by court order, agreement or
|
543 |
+
otherwise) that contradict the conditions of this License, they do not
|
544 |
+
excuse you from the conditions of this License. If you cannot convey a
|
545 |
+
covered work so as to satisfy simultaneously your obligations under this
|
546 |
+
License and any other pertinent obligations, then as a consequence you may
|
547 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
548 |
+
to collect a royalty for further conveying from those to whom you convey
|
549 |
+
the Program, the only way you could satisfy both those terms and this
|
550 |
+
License would be to refrain entirely from conveying the Program.
|
551 |
+
|
552 |
+
13. Use with the GNU Affero General Public License.
|
553 |
+
|
554 |
+
Notwithstanding any other provision of this License, you have
|
555 |
+
permission to link or combine any covered work with a work licensed
|
556 |
+
under version 3 of the GNU Affero General Public License into a single
|
557 |
+
combined work, and to convey the resulting work. The terms of this
|
558 |
+
License will continue to apply to the part which is the covered work,
|
559 |
+
but the special requirements of the GNU Affero General Public License,
|
560 |
+
section 13, concerning interaction through a network will apply to the
|
561 |
+
combination as such.
|
562 |
+
|
563 |
+
14. Revised Versions of this License.
|
564 |
+
|
565 |
+
The Free Software Foundation may publish revised and/or new versions of
|
566 |
+
the GNU General Public License from time to time. Such new versions will
|
567 |
+
be similar in spirit to the present version, but may differ in detail to
|
568 |
+
address new problems or concerns.
|
569 |
+
|
570 |
+
Each version is given a distinguishing version number. If the
|
571 |
+
Program specifies that a certain numbered version of the GNU General
|
572 |
+
Public License "or any later version" applies to it, you have the
|
573 |
+
option of following the terms and conditions either of that numbered
|
574 |
+
version or of any later version published by the Free Software
|
575 |
+
Foundation. If the Program does not specify a version number of the
|
576 |
+
GNU General Public License, you may choose any version ever published
|
577 |
+
by the Free Software Foundation.
|
578 |
+
|
579 |
+
If the Program specifies that a proxy can decide which future
|
580 |
+
versions of the GNU General Public License can be used, that proxy's
|
581 |
+
public statement of acceptance of a version permanently authorizes you
|
582 |
+
to choose that version for the Program.
|
583 |
+
|
584 |
+
Later license versions may give you additional or different
|
585 |
+
permissions. However, no additional obligations are imposed on any
|
586 |
+
author or copyright holder as a result of your choosing to follow a
|
587 |
+
later version.
|
588 |
+
|
589 |
+
15. Disclaimer of Warranty.
|
590 |
+
|
591 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
592 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
593 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
594 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
595 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
596 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
597 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
598 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
599 |
+
|
600 |
+
16. Limitation of Liability.
|
601 |
+
|
602 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
603 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
604 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
605 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
606 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
607 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
608 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
609 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
610 |
+
SUCH DAMAGES.
|
611 |
+
|
612 |
+
17. Interpretation of Sections 15 and 16.
|
613 |
+
|
614 |
+
If the disclaimer of warranty and limitation of liability provided
|
615 |
+
above cannot be given local legal effect according to their terms,
|
616 |
+
reviewing courts shall apply local law that most closely approximates
|
617 |
+
an absolute waiver of all civil liability in connection with the
|
618 |
+
Program, unless a warranty or assumption of liability accompanies a
|
619 |
+
copy of the Program in return for a fee.
|
620 |
+
|
621 |
+
END OF TERMS AND CONDITIONS
|
622 |
+
|
623 |
+
How to Apply These Terms to Your New Programs
|
624 |
+
|
625 |
+
If you develop a new program, and you want it to be of the greatest
|
626 |
+
possible use to the public, the best way to achieve this is to make it
|
627 |
+
free software which everyone can redistribute and change under these terms.
|
628 |
+
|
629 |
+
To do so, attach the following notices to the program. It is safest
|
630 |
+
to attach them to the start of each source file to most effectively
|
631 |
+
state the exclusion of warranty; and each file should have at least
|
632 |
+
the "copyright" line and a pointer to where the full notice is found.
|
633 |
+
|
634 |
+
<one line to give the program's name and a brief idea of what it does.>
|
635 |
+
Copyright (C) <year> <name of author>
|
636 |
+
|
637 |
+
This program is free software: you can redistribute it and/or modify
|
638 |
+
it under the terms of the GNU General Public License as published by
|
639 |
+
the Free Software Foundation, either version 3 of the License, or
|
640 |
+
(at your option) any later version.
|
641 |
+
|
642 |
+
This program is distributed in the hope that it will be useful,
|
643 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
644 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
645 |
+
GNU General Public License for more details.
|
646 |
+
|
647 |
+
You should have received a copy of the GNU General Public License
|
648 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
649 |
+
|
650 |
+
Also add information on how to contact you by electronic and paper mail.
|
651 |
+
|
652 |
+
If the program does terminal interaction, make it output a short
|
653 |
+
notice like this when it starts in an interactive mode:
|
654 |
+
|
655 |
+
<program> Copyright (C) <year> <name of author>
|
656 |
+
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
657 |
+
This is free software, and you are welcome to redistribute it
|
658 |
+
under certain conditions; type `show c' for details.
|
659 |
+
|
660 |
+
The hypothetical commands `show w' and `show c' should show the appropriate
|
661 |
+
parts of the General Public License. Of course, your program's commands
|
662 |
+
might be different; for a GUI interface, you would use an "about box".
|
663 |
+
|
664 |
+
You should also get your employer (if you work as a programmer) or school,
|
665 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
666 |
+
For more information on this, and how to apply and follow the GNU GPL, see
|
667 |
+
<https://www.gnu.org/licenses/>.
|
668 |
+
|
669 |
+
The GNU General Public License does not permit incorporating your program
|
670 |
+
into proprietary programs. If your program is a subroutine library, you
|
671 |
+
may consider it more useful to permit linking proprietary applications with
|
672 |
+
the library. If this is what you want to do, use the GNU Lesser General
|
673 |
+
Public License instead of this License. But first, please read
|
674 |
+
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
quip-sharp/README.md
ADDED
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# QuIP#: [QuIP](https://github.com/jerry-chee/QuIP) with Lattice Codebooks
|
2 |
+
This repository contains the official code for **QuIP#**, a weights-only quantization method that is able to achieve near fp16 performance using only 2 bits per weight.
|
3 |
+
QuIP# combines lattice codebooks with incoherence processing to create state-of-the-art 2 bit quantized models.
|
4 |
+
We provide a full suite of 2 bit Llama models quantized using QuIP# as well as other Llama-architecture models (e.g. Mistral).
|
5 |
+
We also provide a full codebase that allows users to quantize and deploy their own models as well as CUDA kernels that accelerate inference for QuIP# models.
|
6 |
+
|
7 |
+
| Method | Precision | Wiki $\downarrow$ | C4 $\downarrow$ | ArcE $\uparrow$ | PiQA $\uparrow$ |
|
8 |
+
|:---------:|:---------:|:---------:|:---------:|:---------:|:---------:|
|
9 |
+
| Native | 16 bit | 3.120 | 5.533 | 0.597 | 0.809 |
|
10 |
+
| OPTQ | 3 bit | 4.577 | 6.838 | 0.544 | **0.786** |
|
11 |
+
| OPTQ | 2 bit | 109.820 | 62.692 | 0.253 | 0.505 |
|
12 |
+
| QuIP | 2 bit | 5.574 | 8.268 | 0.544 | 0.751 |
|
13 |
+
| **QuIP#** | **2 bit** | **4.156** | **6.545** | **0.595** | 0.785 |
|
14 |
+
|
15 |
+
Quantization results on Llama 2 70B. QuIP# achieves near-native performance at 2 bits, outperforming all other presented baselines.
|
16 |
+
|
17 |
+
## ☞ Read more about QuIP# and how it works [here](https://cornell-relaxml.github.io/quip-sharp/)!
|
18 |
+
|
19 |
+
## News
|
20 |
+
|
21 |
+
- We have "deprecated" the 2 bit D4 quantized models as they perform worse than 2 bit E8P models and are slower to run. The code to quantize and run D4 models is still in the codebase, but the D4 models have been removed from HF and we are no longer actively supporting them.
|
22 |
+
- We recently added 2 and 4 bit quantized versions of [Mistral 7B](https://huggingface.co/mistralai/Mistral-7B-v0.1) and [OpenHermes 2.5](https://huggingface.co/teknium/OpenHermes-2.5-Mistral-7B). See the Model Zoo section for more details.
|
23 |
+
- **The 4 bit models have been replaced by new bit-packed models that end with the `-Packed` suffix. The old models have been deprecated, removed, and do not work with the current code (and vice versa). Make sure to pull the latest code to run the 4 bit models.**
|
24 |
+
|
25 |
+
## Installation
|
26 |
+
|
27 |
+
- Clone the repo
|
28 |
+
- Install the requirements via `pip install -r requirements.txt`. You may want to use the official pytorch commands to get the CUDA versions.
|
29 |
+
- Build and install the matmul CUDA kernels. (`cd quiptools && python setup.py install && cd ../`)
|
30 |
+
|
31 |
+
## Quantization
|
32 |
+
|
33 |
+
- To quantize a Llama architecture (q/k/v/o/up/gate/down) model: `python quantize_llama.py --<FLAGS>`. The primary flags are as follows. See the arg list for the remaining flags.
|
34 |
+
- `--save_path <output path>`.
|
35 |
+
- `--base_model <Hugging Face (HF) model card or local path>`.
|
36 |
+
For Llama 1, we provide weights at `relaxml/Llama-1-<7,13,30,65>b-hf`. For other models, use model cards from HF.
|
37 |
+
- `--hessian_path <path to precomputed Hessians>`.
|
38 |
+
We provide precomputed Hessians at repo_id's `relaxml/Hessians*-<n>`. These Hessians were computed with `n` samples and the context length and attention mask used to train the original model. To download them, run `python scripts/download_hf.py --folder_path <local path to save Hessians> --repo_id <repo_id> --read_token <huggingface read token>`.
|
39 |
+
- `--codebook <codebook argument>`.
|
40 |
+
We recommend using the 2 bit E8P codebook with `E8P12`. This codebook gives the best quantization at 2 bits. Other options are the 2 bit `D4` codebook and the 4 bit Half Integer grid `HI4B1C`. See our blog post for details on the codebooks.
|
41 |
+
- `--scale_override <quantization scale parameter>`.
|
42 |
+
We suggest the following scale parameters for each codebook: `{E8P12: 0.9, D4: 1.1, HI4B1C: 2.7}`, however you may want to play around with scales if quantizing your own models.
|
43 |
+
- To convert a quantized model to the HF format: `CUDA_VISIBLE_DEVICES=0 python hfize_llama.py --quantized_path <output path of quantize_llama.py> --hf_output_path <path to save HF version>`
|
44 |
+
- To generate your own Hessians for a Llama architecture model: `python hessian_offline_llama --<FLAGS>`. The primary flags are as follows. See the arg list for the remaining flags. **Hessian calculation uses a `fp64` accumulator for numerical accuracy. Running this script on a device with slow `fp64` capabilities will take longer.**
|
45 |
+
- `--batch_size` Batch size per GPU. Tune so you don't run out of memory.
|
46 |
+
- `--devset_size` Size of devset to use for Hessian generation.
|
47 |
+
- `--ctx_size` Context size (sequence length) to use for Hessian generation.
|
48 |
+
- `--base_model` Same as in `quantize_llama.py`.
|
49 |
+
|
50 |
+
### I want to quantize a non-Llama architecture model, what do I do?
|
51 |
+
|
52 |
+
Currently, `hessian_offline_llama.py`, `quantize_llama.py`, and `hfize_llama.py` are written for the Llama architecture. However, the only "special" things they do are identify the relevant `nn.Linear` layers that need to be quantized (q/k/v/o/up/gate/down), inject Hessian hooks, and quantize them.
|
53 |
+
If you want to quantize a non-Llama architecture model, you will need to find the relevant `nn.Linear` files and make your own hessian_offline/quantize/hfize files. This should be pretty straightforward and feel free to open a GitHub ticket if you run into any issues.
|
54 |
+
You will also need copy `modeling_<architecture>.py` from the HF source into the `models/` folder and replace the relevant `nn.Linear` layers with `QuantizedLinear` layers (see how `models/llama.py` does it).
|
55 |
+
Our current `quantize_llama.py` implementation fuses the q/k/v layers and the up/gate layers for increased speed since they share the same Hessians. However, this is not a requirement and you can also quantize those layers individually.
|
56 |
+
|
57 |
+
|
58 |
+
## Evaluation
|
59 |
+
|
60 |
+
See our blog post for a full set of results.
|
61 |
+
- Perplexity on Wikitext2 and C4: `CUDA_VISIBLE_DEVICES=0 python eval_ppl.py --hf_path <HF version path>`
|
62 |
+
- Zero shot tasks: `CUDA_VISIBLE_DEVICES=0 python eval_zeroshot.py --tasks arc_challenge,arc_easy,boolq,piqa,winogrande --batch_size <batch size> --hf_path <HF version path>`
|
63 |
+
- Timing test for forward pass of one token: `CUDA_VISIBLE_DEVICES=0 python gen_speed.py --hf_path <HF version path> --batch_size <batch_size>`.
|
64 |
+
|
65 |
+
*The `CUDA_VISIBLE_DEVICES` environmental variable is only needed if you get CUDA errors from running on more GPUs than needed to fit the model. This is an artifact of HF accelerate.*
|
66 |
+
|
67 |
+
## Text Generation
|
68 |
+
|
69 |
+
To use our models as part of an interactive generation script, run `CUDA_VISIBLE_DEVICES=0 python interactive_gen.py --hf_path <HF version path> --max_length <max generation length>`.
|
70 |
+
`interactive_gen.py` is very rudimentary and you may want to write your own.
|
71 |
+
All it does is call HF's `.generate()` function.
|
72 |
+
|
73 |
+
## Model Zoo
|
74 |
+
We provide quantized models available on HF.
|
75 |
+
To use them, pass the given HF repo_id to `--hf_path`.
|
76 |
+
We recommend using the `E8P` codebook which quantizes to 2 bits per weight, which gives the best quantization at 2 bits.
|
77 |
+
See our blogpost for details on the codebooks.
|
78 |
+
|
79 |
+
| Lattice Codebook | Base Model | Weight Bits | HF repo_id |
|
80 |
+
|:----------------:|:-----------|:-----------:|:----------------|
|
81 |
+
| E8P (recommended)| Llama 2 70b | 2 | [`relaxml/Llama-2-70b-E8P-2Bit`](https://huggingface.co/relaxml/Llama-2-70b-E8P-2Bit) |
|
82 |
+
| | Llama 2 70b chat| 2 | [`relaxml/Llama-2-70b-chat-E8P-2Bit`](https://huggingface.co/relaxml/Llama-2-70b-chat-E8P-2Bit) |
|
83 |
+
| | Llama 2 13b | 2 | [`relaxml/Llama-2-13b-E8P-2Bit`](https://huggingface.co/relaxml/Llama-2-13b-E8P-2Bit) |
|
84 |
+
| | Llama 2 13b chat| 2 | [`relaxml/Llama-2-13b-chat-E8P-2Bit`](https://huggingface.co/relaxml/Llama-2-13b-chat-E8P-2Bit) |
|
85 |
+
| | Llama 2 7b | 2 | [`relaxml/Llama-2-7b-E8P-2Bit`](https://huggingface.co/relaxml/Llama-2-7b-E8P-2Bit) |
|
86 |
+
| | Llama 2 7b chat| 2 | [`relaxml/Llama-2-7b-chat-E8P-2Bit`](https://huggingface.co/relaxml/Llama-2-7b-chat-E8P-2Bit) |
|
87 |
+
| | Llama 1 65b | 2 | [`relaxml/Llama-1-65b-E8P-2Bit`](https://huggingface.co/relaxml/Llama-1-65b-E8P-2Bit) |
|
88 |
+
| | Llama 1 30b | 2 | [`relaxml/Llama-1-30b-E8P-2Bit`](https://huggingface.co/relaxml/Llama-1-30b-E8P-2Bit) |
|
89 |
+
| | Llama 1 13b | 2 | [`relaxml/Llama-1-13b-E8P-2Bit`](https://huggingface.co/relaxml/Llama-1-13b-E8P-2Bit) |
|
90 |
+
| | Llama 1 7b | 2 | [`relaxml/Llama-1-7b-E8P-2Bit`](https://huggingface.co/relaxml/Llama-1-7b-E8P-2Bit) |
|
91 |
+
| | Mistral 7b | 2 | [`relaxml/Mistral-7b-E8P-2Bit`](https://huggingface.co/relaxml/Mistral-7b-E8P-2Bit) |
|
92 |
+
| | OpenHermes 2.5 | 2 | [`relaxml/Openhermes-7b-E8P-2Bit`](https://huggingface.co/relaxml/Openhermes-7b-E8P-2Bit) |
|
93 |
+
| HI | Llama 2 70b | 4 | [`relaxml/Llama-2-70b-HI-4Bit-Packed`](https://huggingface.co/relaxml/Llama-2-70b-HI-4Bit-Packed) |
|
94 |
+
| | Llama 2 13b | 4 | [`relaxml/Llama-2-13b-HI-4Bit-Packed`](https://huggingface.co/relaxml/Llama-2-13b-HI-4Bit-Packed) |
|
95 |
+
| | Llama 2 7b | 4 | [`relaxml/Llama-2-7b-HI-4Bit-Packed`](https://huggingface.co/relaxml/Llama-2-7b-HI-4Bit-Packed) |
|
96 |
+
| | Llama 1 65b | 4 | [`relaxml/Llama-1-65b-HI-4Bit-Packed`](https://huggingface.co/relaxml/Llama-1-65b-HI-4Bit-Packed) |
|
97 |
+
| | Llama 1 30b | 4 | [`relaxml/Llama-1-30b-HI-4Bit-Packed`](https://huggingface.co/relaxml/Llama-1-30b-HI-4Bit-Packed) |
|
98 |
+
| | Llama 1 13b | 4 | [`relaxml/Llama-1-13b-HI-4Bit-Packed`](https://huggingface.co/relaxml/Llama-1-13b-HI-4Bit-Packed) |
|
99 |
+
| | Llama 1 7b | 4 | [`relaxml/Llama-1-7b-HI-4Bit-Packed`](https://huggingface.co/relaxml/Llama-1-7b-HI-4Bit-Packed) |
|
100 |
+
| | Mistral 7b | 4 | [`relaxml/Mistral-7b-HI-4Bit-Packed`](https://huggingface.co/relaxml/Mistral-7b-HI-4Bit-Packed) |
|
101 |
+
| | OpenHermes 2.5 | 4 | [`relaxml/Openhermes-7b-HI-4Bit-Packed`](https://huggingface.co/relaxml/Openhermes-7b-HI-4Bit-Packed) |
|
102 |
+
|
103 |
+
|
104 |
+
## CUDA Graphs
|
105 |
+
|
106 |
+
We provide a wrapper class that integrates our models with CUDA graphs in `model/graph_wrapper.py`.
|
107 |
+
Currently, the torch CUDA graph implementation does not work with HF's `.generate()` function, but model calls with static input and output sizes can utilize the CUDA graph wrapper for better performance.
|
108 |
+
Most of our evaluation scripts use the graph wrapper by default unless the `--no_use_cuda_graph` flag is passed in.
|
109 |
+
|
110 |
+
## Other
|
111 |
+
|
112 |
+
Use of Llama models is governed by the Meta license available [here](https://ai.meta.com/resources/models-and-libraries/llama-downloads/).
|
113 |
+
Use of Mistral models is governed by the Apache 2.0 license.
|
114 |
+
Use of this code is governed by the GNU GPL v3 license.
|
quip-sharp/docs/Makefile
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
all:
|
2 |
+
pandoc -s --mathjax index.md -o index.html --metadata=title="QuIP#" --variable=title=""
|
quip-sharp/docs/img/kissing2d.png
ADDED
quip-sharp/docs/img/lattice_err.png
ADDED
quip-sharp/docs/img/overview.svg
ADDED
quip-sharp/docs/index.html
ADDED
@@ -0,0 +1,835 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<!DOCTYPE html>
|
2 |
+
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
|
3 |
+
<head>
|
4 |
+
<meta charset="utf-8" />
|
5 |
+
<meta name="generator" content="pandoc" />
|
6 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
|
7 |
+
<title>QuIP#</title>
|
8 |
+
<style>
|
9 |
+
html {
|
10 |
+
font-family: cambria;
|
11 |
+
font-size: 16pt;
|
12 |
+
color: #1a1a1a;
|
13 |
+
background-color: #fdfdfd;
|
14 |
+
}
|
15 |
+
body {
|
16 |
+
margin: 0 auto;
|
17 |
+
max-width: 36em;
|
18 |
+
padding-left: 50px;
|
19 |
+
padding-right: 50px;
|
20 |
+
padding-top: 50px;
|
21 |
+
padding-bottom: 50px;
|
22 |
+
hyphens: auto;
|
23 |
+
overflow-wrap: break-word;
|
24 |
+
text-rendering: optimizeLegibility;
|
25 |
+
font-kerning: normal;
|
26 |
+
}
|
27 |
+
@media (max-width: 600px) {
|
28 |
+
body {
|
29 |
+
font-size: 0.9em;
|
30 |
+
padding: 12px;
|
31 |
+
}
|
32 |
+
h1 {
|
33 |
+
font-size: 1.8em;
|
34 |
+
}
|
35 |
+
}
|
36 |
+
@media print {
|
37 |
+
html {
|
38 |
+
background-color: white;
|
39 |
+
}
|
40 |
+
body {
|
41 |
+
background-color: transparent;
|
42 |
+
color: black;
|
43 |
+
font-size: 12pt;
|
44 |
+
}
|
45 |
+
p, h2, h3 {
|
46 |
+
orphans: 3;
|
47 |
+
widows: 3;
|
48 |
+
}
|
49 |
+
h2, h3, h4 {
|
50 |
+
page-break-after: avoid;
|
51 |
+
}
|
52 |
+
}
|
53 |
+
p {
|
54 |
+
margin: 1em 0;
|
55 |
+
}
|
56 |
+
a {
|
57 |
+
color: #1a1a1a;
|
58 |
+
}
|
59 |
+
a:visited {
|
60 |
+
color: #1a1a1a;
|
61 |
+
}
|
62 |
+
img {
|
63 |
+
max-width: 100%;
|
64 |
+
}
|
65 |
+
svg {
|
66 |
+
height: auto;
|
67 |
+
max-width: 100%;
|
68 |
+
}
|
69 |
+
h1, h2, h3, h4, h5, h6 {
|
70 |
+
margin-top: 1.4em;
|
71 |
+
}
|
72 |
+
h5, h6 {
|
73 |
+
font-size: 1em;
|
74 |
+
font-style: italic;
|
75 |
+
}
|
76 |
+
h6 {
|
77 |
+
font-weight: normal;
|
78 |
+
}
|
79 |
+
ol, ul {
|
80 |
+
padding-left: 1.7em;
|
81 |
+
margin-top: 1em;
|
82 |
+
}
|
83 |
+
li > ol, li > ul {
|
84 |
+
margin-top: 0;
|
85 |
+
}
|
86 |
+
blockquote {
|
87 |
+
margin: 1em 0 1em 1.7em;
|
88 |
+
padding-left: 1em;
|
89 |
+
border-left: 2px solid #e6e6e6;
|
90 |
+
color: #606060;
|
91 |
+
}
|
92 |
+
code {
|
93 |
+
font-family: Menlo, Monaco, Consolas, 'Lucida Console', monospace;
|
94 |
+
font-size: 85%;
|
95 |
+
margin: 0;
|
96 |
+
hyphens: manual;
|
97 |
+
}
|
98 |
+
pre {
|
99 |
+
margin: 1em 0;
|
100 |
+
overflow: auto;
|
101 |
+
}
|
102 |
+
pre code {
|
103 |
+
padding: 0;
|
104 |
+
overflow: visible;
|
105 |
+
overflow-wrap: normal;
|
106 |
+
}
|
107 |
+
.sourceCode {
|
108 |
+
background-color: transparent;
|
109 |
+
overflow: visible;
|
110 |
+
}
|
111 |
+
hr {
|
112 |
+
background-color: #1a1a1a;
|
113 |
+
border: none;
|
114 |
+
height: 1px;
|
115 |
+
margin: 1em 0;
|
116 |
+
}
|
117 |
+
table {
|
118 |
+
margin: 1em 0;
|
119 |
+
border-collapse: collapse;
|
120 |
+
width: 100%;
|
121 |
+
overflow-x: auto;
|
122 |
+
display: block;
|
123 |
+
font-variant-numeric: lining-nums tabular-nums;
|
124 |
+
}
|
125 |
+
table caption {
|
126 |
+
margin-bottom: 0.75em;
|
127 |
+
}
|
128 |
+
tbody {
|
129 |
+
margin-top: 0.5em;
|
130 |
+
border-top: 1px solid #1a1a1a;
|
131 |
+
border-bottom: 1px solid #1a1a1a;
|
132 |
+
}
|
133 |
+
th {
|
134 |
+
border-top: 1px solid #1a1a1a;
|
135 |
+
padding: 0.25em 0.5em 0.25em 0.5em;
|
136 |
+
}
|
137 |
+
td {
|
138 |
+
padding: 0.125em 0.5em 0.25em 0.5em;
|
139 |
+
}
|
140 |
+
header {
|
141 |
+
margin-bottom: 4em;
|
142 |
+
text-align: center;
|
143 |
+
}
|
144 |
+
#TOC li {
|
145 |
+
list-style: none;
|
146 |
+
}
|
147 |
+
#TOC ul {
|
148 |
+
padding-left: 1.3em;
|
149 |
+
}
|
150 |
+
#TOC > ul {
|
151 |
+
padding-left: 0;
|
152 |
+
}
|
153 |
+
#TOC a:not(:hover) {
|
154 |
+
text-decoration: none;
|
155 |
+
}
|
156 |
+
code{white-space: pre-wrap;}
|
157 |
+
span.smallcaps{font-variant: small-caps;}
|
158 |
+
div.columns{display: flex; gap: min(4vw, 1.5em);}
|
159 |
+
div.column{flex: auto; overflow-x: auto;}
|
160 |
+
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
|
161 |
+
/* The extra [class] is a hack that increases specificity enough to
|
162 |
+
override a similar rule in reveal.js */
|
163 |
+
ul.task-list[class]{list-style: none;}
|
164 |
+
ul.task-list li input[type="checkbox"] {
|
165 |
+
font-size: inherit;
|
166 |
+
width: 0.8em;
|
167 |
+
margin: 0 0.8em 0.2em -1.6em;
|
168 |
+
vertical-align: middle;
|
169 |
+
}
|
170 |
+
</style>
|
171 |
+
<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
|
172 |
+
<script
|
173 |
+
src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml-full.js"
|
174 |
+
type="text/javascript"></script>
|
175 |
+
<!--[if lt IE 9]>
|
176 |
+
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script>
|
177 |
+
<![endif]-->
|
178 |
+
</head>
|
179 |
+
<body>
|
180 |
+
<style>
|
181 |
+
body { max-width: 800px !important; text-align: justify; }
|
182 |
+
tbody {
|
183 |
+
border-top: none;
|
184 |
+
border-bottom: none;
|
185 |
+
}
|
186 |
+
header { height:0px;}
|
187 |
+
tr:nth-child(2n) {
|
188 |
+
background-color: #EEEEEE;
|
189 |
+
}
|
190 |
+
th {
|
191 |
+
background-color: #EEEEEE;
|
192 |
+
}
|
193 |
+
</style>
|
194 |
+
<h2 id="quip-quip-with-lattice-codebooks">QuIP#: <a
|
195 |
+
href="https://github.com/jerry-chee/QuIP">QuIP</a> with Lattice
|
196 |
+
Codebooks</h2>
|
197 |
+
<p><a href="https://tsengalb99.github.io">Albert Tseng*</a>, <a
|
198 |
+
href="https://jerry-chee.github.io/">Jerry Chee*</a>, <a
|
199 |
+
href="https://nalzok.github.io/">Qingyao Sun</a>, <a
|
200 |
+
href="https://www.cs.cornell.edu/~kuleshov/">Volodymyr Kuleshov</a>, and
|
201 |
+
<a href="https://www.cs.cornell.edu/~cdesa/">Chris De Sa</a></p>
|
202 |
+
<hr />
|
203 |
+
<p><img src="img/overview.svg" /></p>
|
204 |
+
<p>Large language models (LLMs) exhibit amazing performance on a wide
|
205 |
+
variety of tasks such as text modeling and code generation. However,
|
206 |
+
they are also very large. For example Llama 2 70B has 70 billion
|
207 |
+
parameters that require 140GB of memory to store in half precision. This
|
208 |
+
presents many challenges, such as needing multiple GPUs just to serve a
|
209 |
+
single LLM. To address these issues, researchers have developed
|
210 |
+
compression methods that reduce the size of models without destroying
|
211 |
+
performance.</p>
|
212 |
+
<p>One class of methods, post-training quantization, compresses trained
|
213 |
+
model weights into lower precision formats to reduce memory
|
214 |
+
requirements. For example, quantizing a model from 16 bit to 2 bit
|
215 |
+
precision would reduce the size of the model by 8x, meaning that even
|
216 |
+
Llama 2 70B would fit on a single 24GB GPU. In this work, we introduce
|
217 |
+
<strong>QuIP#</strong>, which combines lattice codebooks with
|
218 |
+
incoherence processing to create state-of-the-art 2 bit quantized
|
219 |
+
models. These two methods allow QuIP# to significantly close the gap
|
220 |
+
between 2 bit quantized LLMs and unquantized 16 bit models.</p>
|
221 |
+
<div style="margin-left: auto;
|
222 |
+
margin-right: auto;
|
223 |
+
width: 90%;">
|
224 |
+
<table style="width:100%;">
|
225 |
+
<caption>Quantization results on Llama 2 70B. QuIP# achieves near-native
|
226 |
+
performance at 2 bits, outperforming all other presented
|
227 |
+
baselines.</caption>
|
228 |
+
<colgroup>
|
229 |
+
<col style="width: 16%" />
|
230 |
+
<col style="width: 16%" />
|
231 |
+
<col style="width: 16%" />
|
232 |
+
<col style="width: 16%" />
|
233 |
+
<col style="width: 16%" />
|
234 |
+
<col style="width: 16%" />
|
235 |
+
</colgroup>
|
236 |
+
<thead>
|
237 |
+
<tr class="header">
|
238 |
+
<th style="text-align: center;">Method</th>
|
239 |
+
<th style="text-align: center;">Precision</th>
|
240 |
+
<th style="text-align: center;">Wiki <span
|
241 |
+
class="math inline">\(\downarrow\)</span></th>
|
242 |
+
<th style="text-align: center;">C4 <span
|
243 |
+
class="math inline">\(\downarrow\)</span></th>
|
244 |
+
<th style="text-align: center;">ArcE <span
|
245 |
+
class="math inline">\(\uparrow\)</span></th>
|
246 |
+
<th style="text-align: center;">PiQA <span
|
247 |
+
class="math inline">\(\uparrow\)</span></th>
|
248 |
+
</tr>
|
249 |
+
</thead>
|
250 |
+
<tbody>
|
251 |
+
<tr class="odd">
|
252 |
+
<td style="text-align: center;">Native</td>
|
253 |
+
<td style="text-align: center;">16 bit</td>
|
254 |
+
<td style="text-align: center;">3.120</td>
|
255 |
+
<td style="text-align: center;">5.533</td>
|
256 |
+
<td style="text-align: center;">0.597</td>
|
257 |
+
<td style="text-align: center;">0.809</td>
|
258 |
+
</tr>
|
259 |
+
<tr class="even">
|
260 |
+
<td style="text-align: center;">OPTQ</td>
|
261 |
+
<td style="text-align: center;">3 bit</td>
|
262 |
+
<td style="text-align: center;">4.577</td>
|
263 |
+
<td style="text-align: center;">6.838</td>
|
264 |
+
<td style="text-align: center;">0.544</td>
|
265 |
+
<td style="text-align: center;"><strong>0.786</strong></td>
|
266 |
+
</tr>
|
267 |
+
<tr class="odd">
|
268 |
+
<td style="text-align: center;">OPTQ</td>
|
269 |
+
<td style="text-align: center;">2 bit</td>
|
270 |
+
<td style="text-align: center;">109.820</td>
|
271 |
+
<td style="text-align: center;">62.692</td>
|
272 |
+
<td style="text-align: center;">0.253</td>
|
273 |
+
<td style="text-align: center;">0.505</td>
|
274 |
+
</tr>
|
275 |
+
<tr class="even">
|
276 |
+
<td style="text-align: center;">QuIP</td>
|
277 |
+
<td style="text-align: center;">2 bit</td>
|
278 |
+
<td style="text-align: center;">5.574</td>
|
279 |
+
<td style="text-align: center;">8.268</td>
|
280 |
+
<td style="text-align: center;">0.544</td>
|
281 |
+
<td style="text-align: center;">0.751</td>
|
282 |
+
</tr>
|
283 |
+
<tr class="odd">
|
284 |
+
<td style="text-align: center;"><strong>QuIP#</strong></td>
|
285 |
+
<td style="text-align: center;"><strong>2 bit</strong></td>
|
286 |
+
<td style="text-align: center;"><strong>4.156</strong></td>
|
287 |
+
<td style="text-align: center;"><strong>6.545</strong></td>
|
288 |
+
<td style="text-align: center;"><strong>0.595</strong></td>
|
289 |
+
<td style="text-align: center;">0.785</td>
|
290 |
+
</tr>
|
291 |
+
</tbody>
|
292 |
+
</table>
|
293 |
+
</div>
|
294 |
+
<div
|
295 |
+
style="color:steelblue; margin-left: -14%; margin-right: auto; width: 115%">
|
296 |
+
<table>
|
297 |
+
<colgroup>
|
298 |
+
<col style="width: 3%" />
|
299 |
+
<col style="width: 96%" />
|
300 |
+
</colgroup>
|
301 |
+
<tbody>
|
302 |
+
<tr class="odd">
|
303 |
+
<td style="text-align: right;"><span
|
304 |
+
style="font-size:72pt">☞</span></td>
|
305 |
+
<td><strong>Our method, QuIP#, creates 2 bit LLMs that achieve
|
306 |
+
near-native performance, a previously unseen result. We provide a <a
|
307 |
+
href="https://huggingface.co/relaxml">full suite of 2 bit Llama 1 and 2
|
308 |
+
models quantized using QuIP#</a>, as well as a full codebase that allows
|
309 |
+
users to quantize and deploy their own models. We also provide CUDA
|
310 |
+
kernels that accelerate inference for QuIP# models. Our code is
|
311 |
+
available <a
|
312 |
+
href="https://github.com/Cornell-RelaxML/quip-sharp">here</a>.</strong></td>
|
313 |
+
</tr>
|
314 |
+
</tbody>
|
315 |
+
</table>
|
316 |
+
</div>
|
317 |
+
<h3 id="method-overview">Method Overview</h3>
|
318 |
+
<p>QuIP# relies on two main components: <em>incoherence processing</em>
|
319 |
+
and <em>lattice codebooks</em>. Incoherence processing in the context of
|
320 |
+
model quantization was introduced in QuIP. While QuIP used a Kronecker
|
321 |
+
product to perform incoherence processing, we introduce a Hadamard
|
322 |
+
transform-based incoherence approach that is more amenable to fast GPU
|
323 |
+
acceleration.</p>
|
324 |
+
<p>Incoherence-processed weights are approximately Gaussian-distributed,
|
325 |
+
which means that they are suitable for quantizing with symmetric and
|
326 |
+
“round” codebooks. We introduce a new lattice codebook based on the
|
327 |
+
<span class="math inline">\(E_8\)</span> lattice, which achieves the
|
328 |
+
optimal 8 dimension unit ball packing density. Our codebooks are
|
329 |
+
specifically designed to be hardware-friendly by exploiting symmetries
|
330 |
+
in these lattices.</p>
|
331 |
+
<h3 id="quantization-background">Quantization Background</h3>
|
332 |
+
<p>In QuIP#, we follow existing state-of-the-art post training
|
333 |
+
quantization methods and round weights to minimize the per-layer
|
334 |
+
“adaptive rounding” proxy objective</p>
|
335 |
+
<p><span class="math display">\[
|
336 |
+
\ell(\hat W)
|
337 |
+
= E_x \left[ \| (\hat W - W)x \|^2 \right]
|
338 |
+
= \operatorname{tr}\left(
|
339 |
+
(\hat W - W) H (\hat W - W)^T
|
340 |
+
\right).
|
341 |
+
\]</span></p>
|
342 |
+
<p>Here, <span class="math inline">\(W \in \mathbb{R}^{m \times
|
343 |
+
n}\)</span> is the original weight matrix in a given layer, <span
|
344 |
+
class="math inline">\(\hat W = \mathbb{R}^{m \times n}\)</span> are the
|
345 |
+
quantized weights, <span class="math inline">\(x \in
|
346 |
+
\mathbb{R}^n\)</span> is an input vector drawn uniformly at random from
|
347 |
+
a calibration set, and <span class="math inline">\(H\)</span> is the
|
348 |
+
second moment matrix of these vectors, interpreted as a proxy Hessian.
|
349 |
+
This intra-layer formulation makes quantization tracatable for large
|
350 |
+
language models. The original QuIP paper forumlated a class of adaptive
|
351 |
+
rounding methods that used linear feedback to minimize <span
|
352 |
+
class="math inline">\(\ell\)</span>. Within this class, the LDLQ
|
353 |
+
rounding algorithm was shown to be optimal; we use LDLQ in QuIP# as
|
354 |
+
well.</p>
|
355 |
+
<h3 id="incoherence-processing">Incoherence Processing</h3>
|
356 |
+
<p>The main insight of QuIP is that incoherent weight and hessian
|
357 |
+
matrices result in improved quantization performance. Informally, this
|
358 |
+
means that weights that are even in magnitude with important rounding
|
359 |
+
directions (the Hessians) that are not too large in any one coordinate
|
360 |
+
are significantly easier to quantize without catastrophic error. In some
|
361 |
+
sense, incoherence processing can be viewed as a form of outlier
|
362 |
+
suppression across weight and activation spaces.</p>
|
363 |
+
<div style="background-color: #EEEEEE;">
|
364 |
+
<p><strong>Definition.</strong> <em>We say a symmetric Hessian matrix
|
365 |
+
<span class="math inline">\(H \in \mathbb{R}^{n \times n}\)</span> is
|
366 |
+
<span class="math inline">\(\mu\)</span>-incoherent if it has an
|
367 |
+
eigendecomposition <span class="math inline">\(H = Q \Lambda
|
368 |
+
Q^T\)</span> such that for all <span class="math inline">\(i\)</span>
|
369 |
+
and <span class="math inline">\(j\)</span>, <span
|
370 |
+
class="math inline">\(|Q_{ij}| = |e_i^T Q e_j| \leq \mu /
|
371 |
+
\sqrt{n}\)</span>. By extension, we say a weight matrix <span
|
372 |
+
class="math inline">\(W \in \mathbb{R}^{m \times n}\)</span> is <span
|
373 |
+
class="math inline">\(\mu\)</span>-incoherent if for all <span
|
374 |
+
class="math inline">\(i\)</span> and <span
|
375 |
+
class="math inline">\(j\)</span>, <span class="math inline">\(|W_{ij}| =
|
376 |
+
|e_i^T W e_j| \leq \mu \|W\|_F / \sqrt{mn}\)</span>.</em></p>
|
377 |
+
</div>
|
378 |
+
<p>Incoherence is an important property for quantizing models. In QuIP,
|
379 |
+
the incoherence condition on <span class="math inline">\(H\)</span> is
|
380 |
+
required to show that LDLQ achieves a superior proxy loss to nearest and
|
381 |
+
stochastic rounding through a spectral bound on <span
|
382 |
+
class="math inline">\(H\)</span>. Therefore, it is important to be able
|
383 |
+
to incoherence-process weight and hessian matrices efficiently so that
|
384 |
+
incoherence-processed models can be tractably deployed.</p>
|
385 |
+
<p>One way to do this is by conjugating <span
|
386 |
+
class="math inline">\(W\)</span> and <span
|
387 |
+
class="math inline">\(H\)</span> by random orthogonal matrices. Let
|
388 |
+
<span class="math inline">\(U \in \mathbb{R}^{m \times m}\)</span>, and
|
389 |
+
<span class="math inline">\(V \in \mathbb{R}^{n \times n}\)</span> be
|
390 |
+
two random orthogonal matrices. If we assign <span
|
391 |
+
class="math inline">\(\tilde H \gets V H V^T\)</span> and <span
|
392 |
+
class="math inline">\(\tilde W \gets U W V^T\)</span>, <span
|
393 |
+
class="math inline">\(\tilde H\)</span> and <span
|
394 |
+
class="math inline">\(\tilde W\)</span> become incoherence processed
|
395 |
+
with high probability (see QuIP for proof). One can verify that this
|
396 |
+
transformation preserves the proxy objective as <span
|
397 |
+
class="math display">\[\operatorname{tr}(\tilde W \tilde H \tilde W^T) =
|
398 |
+
\operatorname{tr}((U W V^T) (V H V^T) (V W^T U^T)) =
|
399 |
+
\operatorname{tr}(WHW^T).\]</span></p>
|
400 |
+
<h4 id="randomized-hadamard-transformation-rht">Randomized Hadamard
|
401 |
+
Transformation (RHT)</h4>
|
402 |
+
<p>To construct <span class="math inline">\(U\)</span> and <span
|
403 |
+
class="math inline">\(V\)</span> from above, we use the RHT, which is
|
404 |
+
amenable to fast GPU implementation. In fact, one of the CUDA sample
|
405 |
+
kernels is the RHT. The RHT performs the multiplication <span
|
406 |
+
class="math inline">\(x \in \mathbb{R}^n \to \mathbb{H}Sx\)</span>,
|
407 |
+
where <span class="math inline">\(\mathbb{H}\)</span> is a <span
|
408 |
+
class="math inline">\(n \times n\)</span> Hadamard matrix (scaled by a
|
409 |
+
normalization factor) and <span class="math inline">\(S\)</span> is a
|
410 |
+
<span class="math inline">\(n\)</span> dimensional random sign vector.
|
411 |
+
The RHT concentrates the entries of <span
|
412 |
+
class="math inline">\(x\)</span> and thus results in incoherent matrices
|
413 |
+
through an <a
|
414 |
+
href="http://www.cs.cmu.edu/afs/cs/user/dwoodruf/www/teaching/15859-fall20/lecture_2.1.pdf">application
|
415 |
+
of the Azuma-Hoeffding inequality</a>. Note that the Hadamard transform
|
416 |
+
can be computed more efficiently than a matrix multiplication via the
|
417 |
+
fast Walsh-Hadamard transform, which we employ directly for powers of 2.
|
418 |
+
To handle non power-of-two values of <span
|
419 |
+
class="math inline">\(n\)</span>, we perform the following
|
420 |
+
algorithm:</p>
|
421 |
+
<ol type="1">
|
422 |
+
<li>Let <span class="math inline">\(p\)</span> be the remaining
|
423 |
+
dimension and reshape <span class="math inline">\(Sx\)</span> into a
|
424 |
+
<span class="math inline">\(n/p \times p\)</span> matrix.</li>
|
425 |
+
<li>Perform the fast Walsh-Hadamard transform on <span
|
426 |
+
class="math inline">\(Sx\)</span> associated with dimension <span
|
427 |
+
class="math inline">\(n/p\)</span>.</li>
|
428 |
+
<li>Let <span class="math inline">\(\mathbb{H}'\)</span> be a <span
|
429 |
+
class="math inline">\(p \times p\)</span> scaled Hadamard matrix. Apply
|
430 |
+
this Hadamard transform to <span class="math inline">\(Sx\)</span> on
|
431 |
+
the right, and reshape back.</li>
|
432 |
+
</ol>
|
433 |
+
<p>The only consequence of performing RHT is needing to store two sign
|
434 |
+
vectors per layer: <span class="math inline">\(S_U\)</span> and <span
|
435 |
+
class="math inline">\(S_V\)</span>. Since large language models have
|
436 |
+
large weight and Hessian matrices, this only increases the number of
|
437 |
+
bits per weight in practice by less than 0.01, or a negligible
|
438 |
+
amount.</p>
|
439 |
+
<h3 id="lattice-codebooks">Lattice Codebooks</h3>
|
440 |
+
<p>Incoherence processed weights are approximately Gaussian-distributed,
|
441 |
+
meaning that they are symmetric and “round.” To take advantage of this
|
442 |
+
“roundness,” we can use <span class="math inline">\(n\)</span>
|
443 |
+
dimensional codebooks that quantize <span
|
444 |
+
class="math inline">\(n\)</span> weights at once. Specifically, to
|
445 |
+
quantize <span class="math inline">\(x \in \mathbb{R}^n\)</span> to a
|
446 |
+
<span class="math inline">\(n\)</span> dimensional codebook <span
|
447 |
+
class="math inline">\(C \in \mathbb{R}^{m \times n}\)</span>, we round
|
448 |
+
<span class="math inline">\(x\)</span> to its nearest distance-wise
|
449 |
+
entry in <span class="math inline">\(C\)</span>. This requires <span
|
450 |
+
class="math inline">\(\log_2m\)</span> bits to represent which index in
|
451 |
+
<span class="math inline">\(C\)</span> to store, and results in <span
|
452 |
+
class="math inline">\(k = \frac{\log_2m}{n}\)</span> bits per
|
453 |
+
weight.</p>
|
454 |
+
<p>Increasing <span class="math inline">\(n\)</span> results in a
|
455 |
+
“rounder” codebook that reduces quantization error. However, note that
|
456 |
+
the number of bits per weight is determined by <em>both</em> the number
|
457 |
+
of entries in <span class="math inline">\(C\)</span> (m) as well as the
|
458 |
+
dimension of <span class="math inline">\(C\)</span> (n). To maintain a
|
459 |
+
set number of bits per weight, a linear increase in <span
|
460 |
+
class="math inline">\(n\)</span> requires an exponential increase in
|
461 |
+
<span class="math inline">\(m\)</span>. For example, a naively designed
|
462 |
+
16-dimensional codebook requires <span
|
463 |
+
class="math inline">\(2^{32}\)</span> entries to achieve 2 bits per
|
464 |
+
weight, but performing lookups into a size <span
|
465 |
+
class="math inline">\(2^{32}\)</span> codebook is intractable. Thus, it
|
466 |
+
is important to design codebooks that both have relatively large <span
|
467 |
+
class="math inline">\(n\)</span> while being compressible so the actual
|
468 |
+
lookup happens with less than <span
|
469 |
+
class="math inline">\(2^{nk}\)</span> entries.</p>
|
470 |
+
<p>Geometric lattices are suitable bases for such codebooks as most
|
471 |
+
lattices have inherent symmetries and certain lattices achieve optimal
|
472 |
+
bin packing densities. For example, our E8P codebook based on the <span
|
473 |
+
class="math inline">\(E_8\)</span> lattice has <span
|
474 |
+
class="math inline">\(2^{16}\)</span> entries but only requires looking
|
475 |
+
up into a size <span class="math inline">\(2^8\)</span> codebook due to
|
476 |
+
symmetries inherent to the <span class="math inline">\(E_8\)</span>
|
477 |
+
lattice itself – more on this later. In QuIP#, we present the E8P
|
478 |
+
codebook based on the 8-dimensional <span
|
479 |
+
class="math inline">\(E_8\)</span> lattice. This lattice achieves the 8
|
480 |
+
dimensional kissing number, or the maximum number of unit balls touching
|
481 |
+
a central unit ball in 8 dimensions. Interestingly, Maryna Viazovska
|
482 |
+
recently won the Fields Medal in 2022 “for the proof that the <span
|
483 |
+
class="math inline">\(E_8\)</span> lattice provides the densest packing
|
484 |
+
of identical spheres in 8 dimensions.”</p>
|
485 |
+
<figure>
|
486 |
+
<img src="img/kissing2d.png"
|
487 |
+
alt="The 2D kissing number is 6, which is achieved by this packing configuration. Image from Wikipedia." />
|
488 |
+
<figcaption aria-hidden="true">The 2D kissing number is 6, which is
|
489 |
+
achieved by this packing configuration. Image from
|
490 |
+
Wikipedia.</figcaption>
|
491 |
+
</figure>
|
492 |
+
<h4 id="e8p-codebook">E8P Codebook</h4>
|
493 |
+
<p>Our E8P codebook is a version of the <span
|
494 |
+
class="math inline">\(E_8\)</span> lattice intersected with a ball,
|
495 |
+
padded (hence the P in E8P) to reach <span
|
496 |
+
class="math inline">\(2^{16}\)</span> entries. This results in <span
|
497 |
+
class="math inline">\(k = 16/8 = 2\)</span> bits per weight. The <span
|
498 |
+
class="math inline">\(E_8\)</span> lattice is composed of 8 dimensional
|
499 |
+
all-integer or all-half integer vectors whose sum is an even number. In
|
500 |
+
set-builder notation, <span class="math display">\[E_8 = \left\{x \mid x
|
501 |
+
\in \left(\mathbb{Z}^8 \cup \left(\mathbb{Z}+\frac{1}{2}\right)^8\right)
|
502 |
+
\land \sum_i x_i \equiv 0 \pmod 2\right\}.\]</span> Note that <span
|
503 |
+
class="math inline">\(E_8 + \frac{1}{4}\)</span> has the same packing
|
504 |
+
density of <span class="math inline">\(E_8\)</span> and is equivalent to
|
505 |
+
<span class="math inline">\(D_8 + \frac{1}{2} \pm \frac{1}{4}\)</span>,
|
506 |
+
where <span class="math inline">\(D_8\)</span> is the set of 8
|
507 |
+
dimensional all-integer vectors with even sum. Denote <span
|
508 |
+
class="math inline">\(D_8 + \frac{1}{2}\)</span> as <span
|
509 |
+
class="math inline">\(\hat{D_8}\)</span>; all elements in <span
|
510 |
+
class="math inline">\(\hat{D_8}\)</span> also have even sum parity.</p>
|
511 |
+
<p>Now, note that if we flip an even number of signs of an element in
|
512 |
+
<span class="math inline">\(\hat{D_8}\)</span>, we get another element
|
513 |
+
in <span class="math inline">\(\hat{D_8}\)</span>, whereas flipping an
|
514 |
+
odd number of signs results in something not in <span
|
515 |
+
class="math inline">\(\hat{D_8}\)</span>. This is due to <span
|
516 |
+
class="math inline">\(\hat{D_8}\)</span> being a half integer grid;
|
517 |
+
flipping a single half integer results in changing the sum parity. Since
|
518 |
+
<span class="math inline">\(\hat{D_8}\)</span> has 8 dimensions, there
|
519 |
+
are <span class="math inline">\(2^8/2 = 128\)</span> possible “even sign
|
520 |
+
flip” patterns to stay within <span
|
521 |
+
class="math inline">\(\hat{D_8}\)</span>. Conversely, there are also 128
|
522 |
+
“odd sign flip” patterns.</p>
|
523 |
+
<p>If we start from some “source codebook” <span
|
524 |
+
class="math inline">\(S\)</span> that is a subset of <span
|
525 |
+
class="math inline">\(|\hat{D_8}|\)</span>, where <span
|
526 |
+
class="math inline">\(|\cdot|\)</span> denotes the elementwise absolute
|
527 |
+
value, we can use 128 odd or even sign flips to generate a subset of
|
528 |
+
<span class="math inline">\(\hat{D_8}\)</span>. Each entry in <span
|
529 |
+
class="math inline">\(S\)</span> is either an odd or even number of
|
530 |
+
flips away from an entry in <span
|
531 |
+
class="math inline">\(\hat{D_8}\)</span>, but not both. Thus, given an
|
532 |
+
entry <span class="math inline">\(s \in S\)</span> and 7 out of the 8
|
533 |
+
sign flips, we can infer the last one from the parity of the 7 sign
|
534 |
+
flips and <span class="math inline">\(s\)</span>. This lets us use the
|
535 |
+
following bit pattern to store a 16-bit codeword in <span
|
536 |
+
class="math inline">\(E_8 + \frac{1}{4}\)</span>: 8 bits for the entry
|
537 |
+
index in <span class="math inline">\(S\)</span>, 7 bits for the sign
|
538 |
+
flips of the right 7 dimensions of the entry in <span
|
539 |
+
class="math inline">\(S\)</span>, and 1 bit to add or subtract <span
|
540 |
+
class="math inline">\(\frac{1}{4}\)</span>.</p>
|
541 |
+
<p>For example, if we had the codeword <code>0001010110010111</code>,
|
542 |
+
the first 8 bits <code>00010101</code> = 21 would indicate that we start
|
543 |
+
with the 21st entry in <span class="math inline">\(S\)</span>. In this
|
544 |
+
example, let this be the vector</p>
|
545 |
+
<p><span class="math display">\[\left\{\frac{1}{2}, \frac{1}{2},
|
546 |
+
\frac{1}{2}, \frac{3}{2}, \frac{1}{2}, \frac{1}{2}, \frac{1}{2},
|
547 |
+
\frac{1}{2}\right\},\]</span></p>
|
548 |
+
<p>which is not in <span class="math inline">\(\hat{D_8}\)</span>. Thus,
|
549 |
+
<span class="math inline">\(s\)</span> requires an odd number of sign
|
550 |
+
flips to get into <span class="math inline">\(\hat{D_8}\)</span>. Then,
|
551 |
+
the next 7 bits <code>1001011</code> would indicate that we need to
|
552 |
+
negate the 1st, 2nd, 4th, and 7th from right bits. Since we need an odd
|
553 |
+
number of sign flips, the 8th from right bit is also a sign flip. The
|
554 |
+
sign-decoded vector is then</p>
|
555 |
+
<p><span class="math display">\[\left\{-\frac{1}{2}, -\frac{1}{2},
|
556 |
+
\frac{1}{2}, \frac{3}{2}, -\frac{1}{2}, \frac{1}{2}, -\frac{1}{2},
|
557 |
+
-\frac{1}{2}\right\},\]</span></p>
|
558 |
+
<p>which we can verify is in <span class="math inline">\(E_8\)</span>.
|
559 |
+
Finally, the last bit <code>1</code> indicates that we need to add <span
|
560 |
+
class="math inline">\(\frac{1}{4}\)</span>, so the final decoded vector
|
561 |
+
is</p>
|
562 |
+
<p><span class="math display">\[\left\{-\frac{1}{4}, -\frac{3}{4},
|
563 |
+
\frac{3}{4}, \frac{7}{4}, -\frac{1}{4}, \frac{3}{4}, -\frac{1}{4},
|
564 |
+
-\frac{1}{4}\right\},\]</span></p>
|
565 |
+
<p>which is in <span class="math inline">\(E_8 + \frac{1}{4}\)</span> as
|
566 |
+
desired.</p>
|
567 |
+
<p>Putting this all together, this lets us decode a size <span
|
568 |
+
class="math inline">\(2^{16}\)</span> codebook by looking up into only a
|
569 |
+
size <span class="math inline">\(2^8\)</span> codebook (namely <span
|
570 |
+
class="math inline">\(S\)</span>) and performing some operations. On
|
571 |
+
hardware, this means that we can store the smaller <span
|
572 |
+
class="math inline">\(2^8\)</span> codebook in local caches, avoiding
|
573 |
+
performance killing memory accesses that the larger <span
|
574 |
+
class="math inline">\(2^{16}\)</span> codebook would require. The
|
575 |
+
question remains then of how to choose <span
|
576 |
+
class="math inline">\(S\)</span>. In our implementation, we set <span
|
577 |
+
class="math inline">\(S\)</span> to be the 227 elements of <span
|
578 |
+
class="math inline">\(|\hat{D_8}|\)</span> with norm <span
|
579 |
+
class="math inline">\(\le \sqrt{10}\)</span> plus 29 elements from <span
|
580 |
+
class="math inline">\(|\hat{D_8}|\)</span> that have norm <span
|
581 |
+
class="math inline">\(\sqrt{12}\)</span>. The exact elements chosen can
|
582 |
+
be found in our code.</p>
|
583 |
+
<h4 id="codebook-errors">Codebook Errors</h4>
|
584 |
+
<p>To show the optimality of our lattice codebooks, we plotted the
|
585 |
+
minimum achievable elementwise MSE of quantizing a <span
|
586 |
+
class="math inline">\(n\)</span>-dimensional multivariate Gaussian to
|
587 |
+
various <span class="math inline">\(k\)</span> bit codebooks. To create
|
588 |
+
each codebook, we intersected a ball with the base lattice and increased
|
589 |
+
the radius of the ball to get more bits. The half integer codebooks are
|
590 |
+
formed from the <span class="math inline">\(n\)</span>-dimensional half
|
591 |
+
integer grids.</p>
|
592 |
+
<p>Specifically, each point in the graph below plots <span
|
593 |
+
class="math inline">\((k, y)\)</span> where</p>
|
594 |
+
<p><span class="math display">\[y = \min_{s \in \mathbb{R}^+}
|
595 |
+
\frac{1}{n}\left\|\mbox{quantize}\left(\frac{\mathcal{N}(0_n, I_n)}{s},
|
596 |
+
\mbox{codebook}\right)*s - \mathcal{N}(0_n, I_n)\right\|^2\]</span></p>
|
597 |
+
<figure>
|
598 |
+
<img src="img/lattice_err.png" title="Lattice Errors"
|
599 |
+
alt="Lowest element-wise mean squared error (MSE) achievable for quantizing a multivariate Gaussian to various codebooks. The E_8 lattice achieves the densest unit-sphere packing in 8 dimensions and our derivative codebooks have the lowest MSE." />
|
600 |
+
<figcaption aria-hidden="true">Lowest element-wise mean squared error
|
601 |
+
(MSE) achievable for quantizing a multivariate Gaussian to various
|
602 |
+
codebooks. The <span class="math inline">\(E_8\)</span> lattice achieves
|
603 |
+
the <a href="https://en.wikipedia.org/wiki/Kissing_number">densest
|
604 |
+
unit-sphere packing in 8 dimensions</a> and our derivative codebooks
|
605 |
+
have the lowest MSE.</figcaption>
|
606 |
+
</figure>
|
607 |
+
<p>The <span class="math inline">\(E_8\)</span>-based codebooks achieves
|
608 |
+
lower MSEs than all other codebooks, including those based on the <span
|
609 |
+
class="math inline">\(D_4\)</span> lattice that achieves the 4
|
610 |
+
dimensional kissing number. This figure also shows the importance of
|
611 |
+
having a large number of columns <span class="math inline">\(n\)</span>.
|
612 |
+
Increasing the number of columns decreases the error for the half
|
613 |
+
integer grid, as the resulting codebook is more “round.” Since the E8P
|
614 |
+
codebook is actually the union of two shifted codebooks, each of which
|
615 |
+
is a ball intersected with <span
|
616 |
+
class="math inline">\(\hat{D_8}\)</span>, it is not perfectly round.
|
617 |
+
This is reflected in the MSE plot, where it sits slightly above the
|
618 |
+
<span class="math inline">\(E_8\)</span> line. However, there does not
|
619 |
+
exist a <span class="math inline">\(E_8\)</span> codebook with exactly 2
|
620 |
+
bits, so E8P is still practically superior.</p>
|
621 |
+
<h3 id="results">Results</h3>
|
622 |
+
<p>Here, we present quantization results using QuIP# on Llama 1 and 2
|
623 |
+
models. All models were quantized using the Hadamard transform for
|
624 |
+
incoherence processing and a weight scale factor of roughly 0.9 times
|
625 |
+
the optimal scale for a multivariate Gaussian to compensate for
|
626 |
+
inter-layer interactions. Furthermore, all Llama 2 models were evaluated
|
627 |
+
using a context lenth of 4096 and all Llama 1 models were evaluated with
|
628 |
+
context length 2048; these numbers match the context length the models
|
629 |
+
were trained with. These and other models can be found in our <a
|
630 |
+
href="https://huggingface.co/relaxml">Hugging Face repository</a>.</p>
|
631 |
+
<p>The table below contains results for all Llama 1 and 2 models when
|
632 |
+
quantized to 2 bits using the E8P codebook. QuIP# achieves excellent
|
633 |
+
performance across all model sizes on both language modeling and zero
|
634 |
+
shot tasks. Furthermore, on the zero-shot tasks (ArcC, ArcE, BoolQ,
|
635 |
+
PiQA, WinoGrande), QuIP# models achieve near-native performance with
|
636 |
+
minimal degradation. Additional results are available <a
|
637 |
+
href="https://docs.google.com/spreadsheets/d/18woLrIBdVGUr9CuFDbK9pl_6QzEBl09hfnoe4Qkg7Hg/edit?usp=sharing">here</a>.</p>
|
638 |
+
<div style="margin-left: -6%;
|
639 |
+
margin-right: auto;
|
640 |
+
width: 112%;">
|
641 |
+
<table>
|
642 |
+
<caption>QuIP# results across all Llama 1 and 2 models. QuIP# achieves
|
643 |
+
near-native performance at 2 bits on language modeling (C4, Wiki) and
|
644 |
+
zero shot (ArcC, ArcE, BoolQ, PiQA, WinoGrande) tasks.</caption>
|
645 |
+
<colgroup>
|
646 |
+
<col style="width: 6%" />
|
647 |
+
<col style="width: 6%" />
|
648 |
+
<col style="width: 10%" />
|
649 |
+
<col style="width: 11%" />
|
650 |
+
<col style="width: 10%" />
|
651 |
+
<col style="width: 10%" />
|
652 |
+
<col style="width: 12%" />
|
653 |
+
<col style="width: 10%" />
|
654 |
+
<col style="width: 20%" />
|
655 |
+
</colgroup>
|
656 |
+
<thead>
|
657 |
+
<tr class="header">
|
658 |
+
<th style="text-align: center;">Model</th>
|
659 |
+
<th style="text-align: center;">Method</th>
|
660 |
+
<th style="text-align: center;">C4 <span
|
661 |
+
class="math inline">\(\downarrow\)</span></th>
|
662 |
+
<th style="text-align: center;">Wiki <span
|
663 |
+
class="math inline">\(\downarrow\)</span></th>
|
664 |
+
<th style="text-align: center;">ArcC <span
|
665 |
+
class="math inline">\(\uparrow\)</span></th>
|
666 |
+
<th style="text-align: center;">ArcE <span
|
667 |
+
class="math inline">\(\uparrow\)</span></th>
|
668 |
+
<th style="text-align: center;">BoolQ <span
|
669 |
+
class="math inline">\(\uparrow\)</span></th>
|
670 |
+
<th style="text-align: center;">PiQA <span
|
671 |
+
class="math inline">\(\uparrow\)</span></th>
|
672 |
+
<th style="text-align: center;">WinoGrande <span
|
673 |
+
class="math inline">\(\uparrow\)</span></th>
|
674 |
+
</tr>
|
675 |
+
</thead>
|
676 |
+
<tbody>
|
677 |
+
<tr class="odd">
|
678 |
+
<td style="text-align: center;">2-70B</td>
|
679 |
+
<td style="text-align: center;">fp16</td>
|
680 |
+
<td style="text-align: center;">5.533</td>
|
681 |
+
<td style="text-align: center;">3.120</td>
|
682 |
+
<td style="text-align: center;">0.480</td>
|
683 |
+
<td style="text-align: center;">0.597</td>
|
684 |
+
<td style="text-align: center;">0.766</td>
|
685 |
+
<td style="text-align: center;">0.809</td>
|
686 |
+
<td style="text-align: center;">0.768</td>
|
687 |
+
</tr>
|
688 |
+
<tr class="even">
|
689 |
+
<td style="text-align: center;">2-70B</td>
|
690 |
+
<td style="text-align: center;">QuIP#</td>
|
691 |
+
<td style="text-align: center;">6.535</td>
|
692 |
+
<td style="text-align: center;">4.156</td>
|
693 |
+
<td style="text-align: center;">0.469</td>
|
694 |
+
<td style="text-align: center;">0.595</td>
|
695 |
+
<td style="text-align: center;">0.795</td>
|
696 |
+
<td style="text-align: center;">0.785</td>
|
697 |
+
<td style="text-align: center;">0.740</td>
|
698 |
+
</tr>
|
699 |
+
<tr class="odd">
|
700 |
+
<td style="text-align: center;">2-13B</td>
|
701 |
+
<td style="text-align: center;">fp16</td>
|
702 |
+
<td style="text-align: center;">6.520</td>
|
703 |
+
<td style="text-align: center;">4.574</td>
|
704 |
+
<td style="text-align: center;">0.443</td>
|
705 |
+
<td style="text-align: center;">0.580</td>
|
706 |
+
<td style="text-align: center;">0.690</td>
|
707 |
+
<td style="text-align: center;">0.790</td>
|
708 |
+
<td style="text-align: center;">0.699</td>
|
709 |
+
</tr>
|
710 |
+
<tr class="even">
|
711 |
+
<td style="text-align: center;">2-13B</td>
|
712 |
+
<td style="text-align: center;">QuIP#</td>
|
713 |
+
<td style="text-align: center;">8.769</td>
|
714 |
+
<td style="text-align: center;">6.003</td>
|
715 |
+
<td style="text-align: center;">0.381</td>
|
716 |
+
<td style="text-align: center;">0.502</td>
|
717 |
+
<td style="text-align: center;">0.643</td>
|
718 |
+
<td style="text-align: center;">0.751</td>
|
719 |
+
<td style="text-align: center;">0.637</td>
|
720 |
+
</tr>
|
721 |
+
<tr class="odd">
|
722 |
+
<td style="text-align: center;">2-7B</td>
|
723 |
+
<td style="text-align: center;">fp16</td>
|
724 |
+
<td style="text-align: center;">7.036</td>
|
725 |
+
<td style="text-align: center;">5.116</td>
|
726 |
+
<td style="text-align: center;">0.406</td>
|
727 |
+
<td style="text-align: center;">0.535</td>
|
728 |
+
<td style="text-align: center;">0.710</td>
|
729 |
+
<td style="text-align: center;">0.769</td>
|
730 |
+
<td style="text-align: center;">0.670</td>
|
731 |
+
</tr>
|
732 |
+
<tr class="even">
|
733 |
+
<td style="text-align: center;">2-7B</td>
|
734 |
+
<td style="text-align: center;">QuIP#</td>
|
735 |
+
<td style="text-align: center;">12.208</td>
|
736 |
+
<td style="text-align: center;">8.201</td>
|
737 |
+
<td style="text-align: center;">0.346</td>
|
738 |
+
<td style="text-align: center;">0.454</td>
|
739 |
+
<td style="text-align: center;">0.647</td>
|
740 |
+
<td style="text-align: center;">0.726</td>
|
741 |
+
<td style="text-align: center;">0.618</td>
|
742 |
+
</tr>
|
743 |
+
<tr class="odd">
|
744 |
+
<td style="text-align: center;">1-65b</td>
|
745 |
+
<td style="text-align: center;">fp16</td>
|
746 |
+
<td style="text-align: center;">5.811</td>
|
747 |
+
<td style="text-align: center;">3.532</td>
|
748 |
+
<td style="text-align: center;">0.463</td>
|
749 |
+
<td style="text-align: center;">0.588</td>
|
750 |
+
<td style="text-align: center;">0.823</td>
|
751 |
+
<td style="text-align: center;">0.809</td>
|
752 |
+
<td style="text-align: center;">0.771</td>
|
753 |
+
</tr>
|
754 |
+
<tr class="even">
|
755 |
+
<td style="text-align: center;">1-65b</td>
|
756 |
+
<td style="text-align: center;">QuIP#</td>
|
757 |
+
<td style="text-align: center;">6.749</td>
|
758 |
+
<td style="text-align: center;">4.573</td>
|
759 |
+
<td style="text-align: center;">0.435</td>
|
760 |
+
<td style="text-align: center;">0.566</td>
|
761 |
+
<td style="text-align: center;">0.831</td>
|
762 |
+
<td style="text-align: center;">0.792</td>
|
763 |
+
<td style="text-align: center;">0.756</td>
|
764 |
+
</tr>
|
765 |
+
<tr class="odd">
|
766 |
+
<td style="text-align: center;">1-30B</td>
|
767 |
+
<td style="text-align: center;">fp16</td>
|
768 |
+
<td style="text-align: center;">6.130</td>
|
769 |
+
<td style="text-align: center;">4.101</td>
|
770 |
+
<td style="text-align: center;">0.453</td>
|
771 |
+
<td style="text-align: center;">0.590</td>
|
772 |
+
<td style="text-align: center;">0.684</td>
|
773 |
+
<td style="text-align: center;">0.801</td>
|
774 |
+
<td style="text-align: center;">0.728</td>
|
775 |
+
</tr>
|
776 |
+
<tr class="even">
|
777 |
+
<td style="text-align: center;">1-30B</td>
|
778 |
+
<td style="text-align: center;">QuIP#</td>
|
779 |
+
<td style="text-align: center;">7.465</td>
|
780 |
+
<td style="text-align: center;">5.311</td>
|
781 |
+
<td style="text-align: center;">0.422</td>
|
782 |
+
<td style="text-align: center;">0.537</td>
|
783 |
+
<td style="text-align: center;">0.659</td>
|
784 |
+
<td style="text-align: center;">0.776</td>
|
785 |
+
<td style="text-align: center;">0.714</td>
|
786 |
+
</tr>
|
787 |
+
<tr class="odd">
|
788 |
+
<td style="text-align: center;">1-13B</td>
|
789 |
+
<td style="text-align: center;">fp16</td>
|
790 |
+
<td style="text-align: center;">6.798</td>
|
791 |
+
<td style="text-align: center;">5.091</td>
|
792 |
+
<td style="text-align: center;">0.444</td>
|
793 |
+
<td style="text-align: center;">0.599</td>
|
794 |
+
<td style="text-align: center;">0.684</td>
|
795 |
+
<td style="text-align: center;">0.792</td>
|
796 |
+
<td style="text-align: center;">0.701</td>
|
797 |
+
</tr>
|
798 |
+
<tr class="even">
|
799 |
+
<td style="text-align: center;">1-13B</td>
|
800 |
+
<td style="text-align: center;">QuIP#</td>
|
801 |
+
<td style="text-align: center;">8.426</td>
|
802 |
+
<td style="text-align: center;">6.353</td>
|
803 |
+
<td style="text-align: center;">0.382</td>
|
804 |
+
<td style="text-align: center;">0.537</td>
|
805 |
+
<td style="text-align: center;">0.665</td>
|
806 |
+
<td style="text-align: center;">0.757</td>
|
807 |
+
<td style="text-align: center;">0.687</td>
|
808 |
+
</tr>
|
809 |
+
<tr class="odd">
|
810 |
+
<td style="text-align: center;">1-7B</td>
|
811 |
+
<td style="text-align: center;">fp16</td>
|
812 |
+
<td style="text-align: center;">7.343</td>
|
813 |
+
<td style="text-align: center;">5.677</td>
|
814 |
+
<td style="text-align: center;">0.415</td>
|
815 |
+
<td style="text-align: center;">0.525</td>
|
816 |
+
<td style="text-align: center;">0.731</td>
|
817 |
+
<td style="text-align: center;">0.774</td>
|
818 |
+
<td style="text-align: center;">0.670</td>
|
819 |
+
</tr>
|
820 |
+
<tr class="even">
|
821 |
+
<td style="text-align: center;">1-7B</td>
|
822 |
+
<td style="text-align: center;">QuIP#</td>
|
823 |
+
<td style="text-align: center;">10.927</td>
|
824 |
+
<td style="text-align: center;">8.146</td>
|
825 |
+
<td style="text-align: center;">0.347</td>
|
826 |
+
<td style="text-align: center;">0.471</td>
|
827 |
+
<td style="text-align: center;">0.673</td>
|
828 |
+
<td style="text-align: center;">0.724</td>
|
829 |
+
<td style="text-align: center;">0.621</td>
|
830 |
+
</tr>
|
831 |
+
</tbody>
|
832 |
+
</table>
|
833 |
+
</div>
|
834 |
+
</body>
|
835 |
+
</html>
|
quip-sharp/docs/index.md
ADDED
@@ -0,0 +1,254 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
mainfont: cambria
|
3 |
+
fontsize: 16pt
|
4 |
+
title: QuIP#
|
5 |
+
display: none
|
6 |
+
---
|
7 |
+
|
8 |
+
<style>
|
9 |
+
body { max-width: 800px !important; text-align: justify; }
|
10 |
+
tbody {
|
11 |
+
border-top: none;
|
12 |
+
border-bottom: none;
|
13 |
+
}
|
14 |
+
header { height:0px;}
|
15 |
+
tr:nth-child(2n) {
|
16 |
+
background-color: #EEEEEE;
|
17 |
+
}
|
18 |
+
th {
|
19 |
+
background-color: #EEEEEE;
|
20 |
+
}
|
21 |
+
</style>
|
22 |
+
|
23 |
+
|
24 |
+
## QuIP#: [QuIP](https://github.com/jerry-chee/QuIP) with Lattice Codebooks
|
25 |
+
|
26 |
+
[Albert Tseng*](https://tsengalb99.github.io), [Jerry Chee*](https://jerry-chee.github.io/), [Qingyao Sun](https://nalzok.github.io/), [Volodymyr Kuleshov](https://www.cs.cornell.edu/~kuleshov/), and [Chris De Sa](https://www.cs.cornell.edu/~cdesa/)
|
27 |
+
|
28 |
+
---
|
29 |
+
|
30 |
+
![](img/overview.svg)
|
31 |
+
|
32 |
+
Large language models (LLMs) exhibit amazing performance on a wide variety of tasks such as text modeling and code generation.
|
33 |
+
However, they are also very large.
|
34 |
+
For example Llama 2 70B has 70 billion parameters that require 140GB of memory to store in half precision.
|
35 |
+
This presents many challenges, such as needing multiple GPUs just to serve a single LLM.
|
36 |
+
To address these issues, researchers have developed compression methods that reduce the size of models without destroying performance.
|
37 |
+
|
38 |
+
One class of methods, post-training quantization, compresses trained model weights into lower precision formats to reduce memory requirements.
|
39 |
+
For example, quantizing a model from 16 bit to 2 bit precision would reduce the size of the model by 8x, meaning that even Llama 2 70B would fit on a single 24GB GPU.
|
40 |
+
In this work, we introduce **QuIP#**, which combines lattice codebooks with incoherence processing to create state-of-the-art 2 bit quantized models.
|
41 |
+
These two methods allow QuIP# to significantly close the gap between 2 bit quantized LLMs and unquantized 16 bit models.
|
42 |
+
|
43 |
+
|
44 |
+
|
45 |
+
<div style="margin-left: auto;
|
46 |
+
margin-right: auto;
|
47 |
+
width: 90%;">
|
48 |
+
|
49 |
+
| Method | Precision | Wiki $\downarrow$ | C4 $\downarrow$ | ArcE $\uparrow$ | PiQA $\uparrow$ |
|
50 |
+
|:---------:|:---------:|:---------:|:---------:|:---------:|:---------:|
|
51 |
+
| Native | 16 bit | 3.120 | 5.533 | 0.597 | 0.809 |
|
52 |
+
| OPTQ | 3 bit | 4.577 | 6.838 | 0.544 | **0.786** |
|
53 |
+
| OPTQ | 2 bit | 109.820 | 62.692 | 0.253 | 0.505 |
|
54 |
+
| QuIP | 2 bit | 5.574 | 8.268 | 0.544 | 0.751 |
|
55 |
+
| **QuIP#** | **2 bit** | **4.156** | **6.545** | **0.595** | 0.785 |
|
56 |
+
|
57 |
+
:Quantization results on Llama 2 70B. QuIP# achieves near-native performance at 2 bits, outperforming all other presented baselines.
|
58 |
+
|
59 |
+
</div>
|
60 |
+
|
61 |
+
|
62 |
+
<div style="color:steelblue; margin-left: -14%; margin-right: auto; width: 115%">
|
63 |
+
|||
|
64 |
+
|-:|--------------------------------------------------------------|
|
65 |
+
|<span style="font-size:72pt">☞</span>| **Our method, QuIP#, creates 2 bit LLMs that achieve near-native performance, a previously unseen result. We provide a [full suite of 2 bit Llama 1 and 2 models quantized using QuIP#](https://huggingface.co/relaxml), as well as a full codebase that allows users to quantize and deploy their own models. We also provide CUDA kernels that accelerate inference for QuIP# models. Our code is available [here](https://github.com/Cornell-RelaxML/quip-sharp).**|
|
66 |
+
|
67 |
+
</div>
|
68 |
+
|
69 |
+
### Method Overview
|
70 |
+
|
71 |
+
QuIP# relies on two main components: *incoherence processing* and *lattice codebooks*.
|
72 |
+
Incoherence processing in the context of model quantization was introduced in QuIP.
|
73 |
+
While QuIP used a Kronecker product to perform incoherence processing, we introduce a Hadamard transform-based incoherence approach that is more amenable to fast GPU acceleration.
|
74 |
+
|
75 |
+
Incoherence-processed weights are approximately Gaussian-distributed, which means that they are suitable for quantizing with symmetric and “round” codebooks.
|
76 |
+
We introduce a new lattice codebook based on the $E_8$ lattice, which achieves the optimal 8 dimension unit ball packing density.
|
77 |
+
Our codebooks are specifically designed to be hardware-friendly by exploiting symmetries in these lattices.
|
78 |
+
|
79 |
+
### Quantization Background
|
80 |
+
|
81 |
+
In QuIP#, we follow existing state-of-the-art post training quantization methods and round weights to minimize the per-layer "adaptive rounding" proxy objective
|
82 |
+
|
83 |
+
$$
|
84 |
+
\ell(\hat W)
|
85 |
+
= E_x \left[ \| (\hat W - W)x \|^2 \right]
|
86 |
+
= \operatorname{tr}\left(
|
87 |
+
(\hat W - W) H (\hat W - W)^T
|
88 |
+
\right).
|
89 |
+
$$
|
90 |
+
|
91 |
+
Here, $W \in \mathbb{R}^{m \times n}$ is the original weight matrix in a given layer, $\hat W = \mathbb{R}^{m \times n}$ are the quantized weights, $x \in \mathbb{R}^n$ is an input vector drawn uniformly at random from a calibration set, and $H$ is the second moment matrix of these vectors, interpreted as a proxy Hessian.
|
92 |
+
This intra-layer formulation makes quantization tracatable for large language models.
|
93 |
+
The original QuIP paper forumlated a class of adaptive rounding methods that used linear feedback to minimize $\ell$.
|
94 |
+
Within this class, the LDLQ rounding algorithm was shown to be optimal; we use LDLQ in QuIP# as well.
|
95 |
+
|
96 |
+
|
97 |
+
### Incoherence Processing
|
98 |
+
|
99 |
+
The main insight of QuIP is that incoherent weight and hessian matrices result in improved quantization performance.
|
100 |
+
Informally, this means that weights that are even in magnitude with important rounding directions (the Hessians) that are not too large in any one coordinate are significantly easier to quantize without catastrophic error.
|
101 |
+
In some sense, incoherence processing can be viewed as a form of outlier suppression across weight and activation spaces.
|
102 |
+
|
103 |
+
<div style="background-color: #EEEEEE;">
|
104 |
+
**Definition.** *We say a symmetric Hessian matrix $H \in \mathbb{R}^{n \times n}$ is $\mu$-incoherent if it has an eigendecomposition $H = Q \Lambda Q^T$ such that for all $i$ and $j$, $|Q_{ij}| = |e_i^T Q e_j| \leq \mu / \sqrt{n}$.
|
105 |
+
By extension, we say a weight matrix $W \in \mathbb{R}^{m \times n}$ is $\mu$-incoherent if for all $i$ and $j$, $|W_{ij}| = |e_i^T W e_j| \leq \mu \|W\|_F / \sqrt{mn}$.*
|
106 |
+
</div>
|
107 |
+
|
108 |
+
Incoherence is an important property for quantizing models.
|
109 |
+
In QuIP, the incoherence condition on $H$ is required to show that LDLQ achieves a superior proxy loss to nearest and stochastic rounding through a spectral bound on $H$.
|
110 |
+
Therefore, it is important to be able to incoherence-process weight and hessian matrices efficiently so that incoherence-processed models can be tractably deployed.
|
111 |
+
|
112 |
+
One way to do this is by conjugating $W$ and $H$ by random orthogonal matrices.
|
113 |
+
Let $U \in \mathbb{R}^{m \times m}$, and $V \in \mathbb{R}^{n \times n}$ be two random orthogonal matrices.
|
114 |
+
If we assign $\tilde H \gets V H V^T$ and $\tilde W \gets U W V^T$, $\tilde H$ and $\tilde W$ become incoherence processed with high probability (see QuIP for proof).
|
115 |
+
One can verify that this transformation preserves the proxy objective as
|
116 |
+
$$\operatorname{tr}(\tilde W \tilde H \tilde W^T) = \operatorname{tr}((U W V^T) (V H V^T) (V W^T U^T)) = \operatorname{tr}(WHW^T).$$
|
117 |
+
|
118 |
+
#### Randomized Hadamard Transformation (RHT)
|
119 |
+
|
120 |
+
To construct $U$ and $V$ from above, we use the RHT, which is amenable to fast GPU implementation.
|
121 |
+
In fact, one of the CUDA sample kernels is the RHT.
|
122 |
+
The RHT performs the multiplication $x \in \mathbb{R}^n \to \mathbb{H}Sx$, where $\mathbb{H}$ is a $n \times n$ Hadamard matrix (scaled by a normalization factor) and $S$ is a $n$ dimensional random sign vector.
|
123 |
+
The RHT concentrates the entries of $x$ and thus results in incoherent matrices through an [application of the Azuma-Hoeffding inequality](http://www.cs.cmu.edu/afs/cs/user/dwoodruf/www/teaching/15859-fall20/lecture_2.1.pdf).
|
124 |
+
Note that the Hadamard transform can be computed more efficiently than a matrix multiplication via the fast Walsh-Hadamard transform, which we employ directly for powers of 2.
|
125 |
+
To handle non power-of-two values of $n$, we perform the following algorithm:
|
126 |
+
|
127 |
+
1. Let $p$ be the remaining dimension and reshape $Sx$ into a $n/p \times p$ matrix.
|
128 |
+
2. Perform the fast Walsh-Hadamard transform on $Sx$ associated with dimension $n/p$.
|
129 |
+
3. Let $\mathbb{H}'$ be a $p \times p$ scaled Hadamard matrix. Apply this Hadamard transform to $Sx$ on the right, and reshape back.
|
130 |
+
|
131 |
+
The only consequence of performing RHT is needing to store two sign vectors per layer: $S_U$ and $S_V$.
|
132 |
+
Since large language models have large weight and Hessian matrices, this only increases the number of bits per weight in practice by less than 0.01, or a negligible amount.
|
133 |
+
|
134 |
+
### Lattice Codebooks
|
135 |
+
|
136 |
+
Incoherence processed weights are approximately Gaussian-distributed, meaning that they are symmetric and “round.”
|
137 |
+
To take advantage of this “roundness,” we can use $n$ dimensional codebooks that quantize $n$ weights at once.
|
138 |
+
Specifically, to quantize $x \in \mathbb{R}^n$ to a $n$ dimensional codebook $C \in \mathbb{R}^{m \times n}$, we round $x$ to its nearest distance-wise entry in $C$.
|
139 |
+
This requires $\log_2m$ bits to represent which index in $C$ to store, and results in $k = \frac{\log_2m}{n}$ bits per weight.
|
140 |
+
|
141 |
+
Increasing $n$ results in a “rounder” codebook that reduces quantization error.
|
142 |
+
However, note that the number of bits per weight is determined by *both* the number of entries in $C$ (m) as well as the dimension of $C$ (n).
|
143 |
+
To maintain a set number of bits per weight, a linear increase in $n$ requires an exponential increase in $m$.
|
144 |
+
For example, a naively designed 16-dimensional codebook requires $2^{32}$ entries to achieve 2 bits per weight, but performing lookups into a size $2^{32}$ codebook is intractable.
|
145 |
+
Thus, it is important to design codebooks that both have relatively large $n$ while being compressible so the actual lookup happens with less than $2^{nk}$ entries.
|
146 |
+
|
147 |
+
Geometric lattices are suitable bases for such codebooks as most lattices have inherent symmetries and certain lattices achieve optimal bin packing densities.
|
148 |
+
For example, our E8P codebook based on the $E_8$ lattice has $2^{16}$ entries but only requires looking up into a size $2^8$ codebook due to symmetries inherent to the $E_8$ lattice itself -- more on this later.
|
149 |
+
In QuIP#, we present the E8P codebook based on the 8-dimensional $E_8$ lattice.
|
150 |
+
This lattice achieves the 8 dimensional kissing number, or the maximum number of unit balls touching a central unit ball in 8 dimensions.
|
151 |
+
Interestingly, Maryna Viazovska recently won the Fields Medal in 2022 “for the proof that the $E_8$ lattice provides the densest packing of identical spheres in 8 dimensions.”
|
152 |
+
|
153 |
+
![The 2D kissing number is 6, which is achieved by this packing configuration. Image from Wikipedia.](img/kissing2d.png)
|
154 |
+
|
155 |
+
#### E8P Codebook
|
156 |
+
|
157 |
+
Our E8P codebook is a version of the $E_8$ lattice intersected with a ball, padded (hence the P in E8P) to reach $2^{16}$ entries.
|
158 |
+
This results in $k = 16/8 = 2$ bits per weight.
|
159 |
+
The $E_8$ lattice is composed of 8 dimensional all-integer or all-half integer vectors whose sum is an even number.
|
160 |
+
In set-builder notation, $$E_8 = \left\{x \mid x \in \left(\mathbb{Z}^8 \cup \left(\mathbb{Z}+\frac{1}{2}\right)^8\right) \land \sum_i x_i \equiv 0 \pmod 2\right\}.$$
|
161 |
+
Note that $E_8 + \frac{1}{4}$ has the same packing density of $E_8$ and is equivalent to $D_8 + \frac{1}{2} \pm \frac{1}{4}$, where $D_8$ is the set of 8 dimensional all-integer vectors with even sum.
|
162 |
+
Denote $D_8 + \frac{1}{2}$ as $\hat{D_8}$; all elements in $\hat{D_8}$ also have even sum parity.
|
163 |
+
|
164 |
+
Now, note that if we flip an even number of signs of an element in $\hat{D_8}$, we get another element in $\hat{D_8}$, whereas flipping an odd number of signs results in something not in $\hat{D_8}$.
|
165 |
+
This is due to $\hat{D_8}$ being a half integer grid; flipping a single half integer results in changing the sum parity.
|
166 |
+
Since $\hat{D_8}$ has 8 dimensions, there are $2^8/2 = 128$ possible "even sign flip" patterns to stay within $\hat{D_8}$.
|
167 |
+
Conversely, there are also 128 "odd sign flip" patterns.
|
168 |
+
|
169 |
+
If we start from some "source codebook" $S$ that is a subset of $|\hat{D_8}|$, where $|\cdot|$ denotes the elementwise absolute value, we can use 128 odd or even sign flips to generate a subset of $\hat{D_8}$.
|
170 |
+
Each entry in $S$ is either an odd or even number of flips away from an entry in $\hat{D_8}$, but not both.
|
171 |
+
Thus, given an entry $s \in S$ and 7 out of the 8 sign flips, we can infer the last one from the parity of the 7 sign flips and $s$.
|
172 |
+
This lets us use the following bit pattern to store a 16-bit codeword in $E_8 + \frac{1}{4}$: 8 bits for the entry index in $S$, 7 bits for the sign flips of the right 7 dimensions of the entry in $S$, and 1 bit to add or subtract $\frac{1}{4}$.
|
173 |
+
|
174 |
+
For example, if we had the codeword `0001010110010111`, the first 8 bits `00010101` = 21 would indicate that we start with the 21st entry in $S$.
|
175 |
+
In this example, let this be the vector
|
176 |
+
|
177 |
+
$$\left\{\frac{1}{2}, \frac{1}{2}, \frac{1}{2}, \frac{3}{2}, \frac{1}{2}, \frac{1}{2}, \frac{1}{2}, \frac{1}{2}\right\},$$
|
178 |
+
|
179 |
+
which is not in $\hat{D_8}$.
|
180 |
+
Thus, $s$ requires an odd number of sign flips to get into $\hat{D_8}$.
|
181 |
+
Then, the next 7 bits `1001011` would indicate that we need to negate the 1st, 2nd, 4th, and 7th from right bits.
|
182 |
+
Since we need an odd number of sign flips, the 8th from right bit is also a sign flip.
|
183 |
+
The sign-decoded vector is then
|
184 |
+
|
185 |
+
$$\left\{-\frac{1}{2}, -\frac{1}{2}, \frac{1}{2}, \frac{3}{2}, -\frac{1}{2}, \frac{1}{2}, -\frac{1}{2}, -\frac{1}{2}\right\},$$
|
186 |
+
|
187 |
+
which we can verify is in $E_8$.
|
188 |
+
Finally, the last bit `1` indicates that we need to add $\frac{1}{4}$, so the final decoded vector is
|
189 |
+
|
190 |
+
$$\left\{-\frac{1}{4}, -\frac{3}{4}, \frac{3}{4}, \frac{7}{4}, -\frac{1}{4}, \frac{3}{4}, -\frac{1}{4}, -\frac{1}{4}\right\},$$
|
191 |
+
|
192 |
+
which is in $E_8 + \frac{1}{4}$ as desired.
|
193 |
+
|
194 |
+
Putting this all together, this lets us decode a size $2^{16}$ codebook by looking up into only a size $2^8$ codebook (namely $S$) and performing some operations.
|
195 |
+
On hardware, this means that we can store the smaller $2^8$ codebook in local caches, avoiding performance killing memory accesses that the larger $2^{16}$ codebook would require.
|
196 |
+
The question remains then of how to choose $S$.
|
197 |
+
In our implementation, we set $S$ to be the 227 elements of $|\hat{D_8}|$ with norm $\le \sqrt{10}$ plus 29 elements from $|\hat{D_8}|$ that have norm $\sqrt{12}$.
|
198 |
+
The exact elements chosen can be found in our code.
|
199 |
+
|
200 |
+
|
201 |
+
#### Codebook Errors
|
202 |
+
|
203 |
+
To show the optimality of our lattice codebooks, we plotted the minimum achievable elementwise MSE of quantizing a $n$-dimensional multivariate Gaussian to various $k$ bit codebooks.
|
204 |
+
To create each codebook, we intersected a ball with the base lattice and increased the radius of the ball to get more bits.
|
205 |
+
The half integer codebooks are formed from the $n$-dimensional half integer grids.
|
206 |
+
|
207 |
+
Specifically, each point in the graph below plots $(k, y)$ where
|
208 |
+
|
209 |
+
$$y = \min_{s \in \mathbb{R}^+} \frac{1}{n}\left\|\mbox{quantize}\left(\frac{\mathcal{N}(0_n, I_n)}{s}, \mbox{codebook}\right)*s - \mathcal{N}(0_n, I_n)\right\|^2$$
|
210 |
+
|
211 |
+
[lattice_err]: img/lattice_err.png "Lattice Errors"
|
212 |
+
![Lowest element-wise mean squared error (MSE) achievable for quantizing a multivariate Gaussian to various codebooks. The $E_8$ lattice achieves the [densest unit-sphere packing in 8 dimensions](https://en.wikipedia.org/wiki/Kissing_number) and our derivative codebooks have the lowest MSE.][lattice_err]
|
213 |
+
|
214 |
+
The $E_8$-based codebooks achieves lower MSEs than all other codebooks, including those based on the $D_4$ lattice that achieves the 4 dimensional kissing number.
|
215 |
+
This figure also shows the importance of having a large number of columns $n$.
|
216 |
+
Increasing the number of columns decreases the error for the half integer grid, as the resulting codebook is more "round."
|
217 |
+
Since the E8P codebook is actually the union of two shifted codebooks, each of which is a ball intersected with $\hat{D_8}$, it is not perfectly round.
|
218 |
+
This is reflected in the MSE plot, where it sits slightly above the $E_8$ line.
|
219 |
+
However, there does not exist a $E_8$ codebook with exactly 2 bits, so E8P is still practically superior.
|
220 |
+
|
221 |
+
### Results
|
222 |
+
|
223 |
+
Here, we present quantization results using QuIP# on Llama 1 and 2 models.
|
224 |
+
All models were quantized using the Hadamard transform for incoherence processing and a weight scale factor of roughly 0.9 times the optimal scale for a multivariate Gaussian to compensate for inter-layer interactions.
|
225 |
+
Furthermore, all Llama 2 models were evaluated using a context lenth of 4096 and all Llama 1 models were evaluated with context length 2048; these numbers match the context length the models were trained with.
|
226 |
+
These and other models can be found in our [Hugging Face repository](https://huggingface.co/relaxml).
|
227 |
+
|
228 |
+
The table below contains results for all Llama 1 and 2 models when quantized to 2 bits using the E8P codebook.
|
229 |
+
QuIP# achieves excellent performance across all model sizes on both language modeling and zero shot tasks.
|
230 |
+
Furthermore, on the zero-shot tasks (ArcC, ArcE, BoolQ, PiQA, WinoGrande), QuIP# models achieve near-native performance with minimal degradation.
|
231 |
+
Additional results are available [here](https://docs.google.com/spreadsheets/d/18woLrIBdVGUr9CuFDbK9pl_6QzEBl09hfnoe4Qkg7Hg/edit?usp=sharing).
|
232 |
+
|
233 |
+
|
234 |
+
<div style="margin-left: -6%;
|
235 |
+
margin-right: auto;
|
236 |
+
width: 112%;">
|
237 |
+
| Model | Method | C4 $\downarrow$ | Wiki $\downarrow$ | ArcC $\uparrow$ | ArcE $\uparrow$ | BoolQ $\uparrow$ | PiQA $\uparrow$ | WinoGrande $\uparrow$ |
|
238 |
+
|:---------:|:---------:|:---------------:|:-----------------:|:---------------:|:---------------:|:-------------------:|:---------------:|:-------------------------------:|
|
239 |
+
| 2-70B | fp16 | 5.533 | 3.120 | 0.480 | 0.597 | 0.766 | 0.809 | 0.768 |
|
240 |
+
| 2-70B | QuIP# | 6.535 | 4.156 | 0.469 | 0.595 | 0.795 | 0.785 | 0.740 |
|
241 |
+
| 2-13B | fp16 | 6.520 | 4.574 | 0.443 | 0.580 | 0.690 | 0.790 | 0.699 |
|
242 |
+
| 2-13B | QuIP# | 8.769 | 6.003 | 0.381 | 0.502 | 0.643 | 0.751 | 0.637 |
|
243 |
+
| 2-7B | fp16 | 7.036 | 5.116 | 0.406 | 0.535 | 0.710 | 0.769 | 0.670 |
|
244 |
+
| 2-7B | QuIP# | 12.208 | 8.201 | 0.346 | 0.454 | 0.647 | 0.726 | 0.618 |
|
245 |
+
| 1-65b | fp16 | 5.811 | 3.532 | 0.463 | 0.588 | 0.823 | 0.809 | 0.771 |
|
246 |
+
| 1-65b | QuIP# | 6.749 | 4.573 | 0.435 | 0.566 | 0.831 | 0.792 | 0.756 |
|
247 |
+
| 1-30B | fp16 | 6.130 | 4.101 | 0.453 | 0.590 | 0.684 | 0.801 | 0.728 |
|
248 |
+
| 1-30B | QuIP# | 7.465 | 5.311 | 0.422 | 0.537 | 0.659 | 0.776 | 0.714 |
|
249 |
+
| 1-13B | fp16 | 6.798 | 5.091 | 0.444 | 0.599 | 0.684 | 0.792 | 0.701 |
|
250 |
+
| 1-13B | QuIP# | 8.426 | 6.353 | 0.382 | 0.537 | 0.665 | 0.757 | 0.687 |
|
251 |
+
| 1-7B | fp16 | 7.343 | 5.677 | 0.415 | 0.525 | 0.731 | 0.774 | 0.670 |
|
252 |
+
| 1-7B | QuIP# | 10.927 | 8.146 | 0.347 | 0.471 | 0.673 | 0.724 | 0.621 |
|
253 |
+
:QuIP# results across all Llama 1 and 2 models. QuIP# achieves near-native performance at 2 bits on language modeling (C4, Wiki) and zero shot (ArcC, ArcE, BoolQ, PiQA, WinoGrande) tasks.
|
254 |
+
</div>
|
quip-sharp/eval_ppl.py
ADDED
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import math
|
3 |
+
import json
|
4 |
+
import argparse
|
5 |
+
import torch
|
6 |
+
import datasets
|
7 |
+
from lib.utils import gptq_data_utils
|
8 |
+
from lib.utils.unsafe_import import model_from_hf_path
|
9 |
+
import random
|
10 |
+
import glog
|
11 |
+
|
12 |
+
from tqdm import tqdm
|
13 |
+
|
14 |
+
torch.set_grad_enabled(False)
|
15 |
+
|
16 |
+
parser = argparse.ArgumentParser()
|
17 |
+
parser.add_argument('--seed', default=0, type=int)
|
18 |
+
parser.add_argument('--hf_path', default='hfized/quantized_hada_70b', type=str)
|
19 |
+
parser.add_argument('--seqlen', default=4096, type=int)
|
20 |
+
parser.add_argument('--no_use_cuda_graph', action='store_true')
|
21 |
+
parser.add_argument('--no_use_flash_attn', action='store_true')
|
22 |
+
|
23 |
+
|
24 |
+
def main(args):
|
25 |
+
datasets = ['wikitext2', 'c4']
|
26 |
+
model, model_str = model_from_hf_path(args.hf_path,
|
27 |
+
use_cuda_graph=not args.no_use_cuda_graph,
|
28 |
+
use_flash_attn=not args.no_use_flash_attn)
|
29 |
+
|
30 |
+
for dataset in datasets:
|
31 |
+
input_tok = gptq_data_utils.get_test_tokens(dataset,
|
32 |
+
seed=args.seed,
|
33 |
+
seqlen=args.seqlen,
|
34 |
+
model=model_str)
|
35 |
+
nsamples = input_tok.numel() // args.seqlen
|
36 |
+
input_tok = input_tok[0, :(args.seqlen * nsamples)].view(nsamples, args.seqlen)
|
37 |
+
|
38 |
+
if not args.no_use_cuda_graph:
|
39 |
+
model.reset()
|
40 |
+
|
41 |
+
loss_fct = torch.nn.CrossEntropyLoss().cuda()
|
42 |
+
acc_loss = 0.0
|
43 |
+
progress = tqdm(range(nsamples))
|
44 |
+
for ii in progress:
|
45 |
+
input = input_tok[ii, :].cuda().view(1, -1)
|
46 |
+
output = model(input,
|
47 |
+
use_cache=False,
|
48 |
+
output_hidden_states=False,
|
49 |
+
output_attentions=False)[0]
|
50 |
+
shift_logits = output[:, :-1, :].contiguous()
|
51 |
+
shift_labels = input[:, 1:]
|
52 |
+
loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
|
53 |
+
acc_loss += loss.item()
|
54 |
+
progress.set_description(f"avg_loss = {acc_loss/(ii+1)}")
|
55 |
+
|
56 |
+
avg_loss = acc_loss / nsamples
|
57 |
+
|
58 |
+
ppl = torch.exp(torch.tensor(avg_loss)).item()
|
59 |
+
glog.info(f'{dataset} perplexity: {ppl}')
|
60 |
+
|
61 |
+
|
62 |
+
if __name__ == '__main__':
|
63 |
+
torch.set_grad_enabled(False)
|
64 |
+
args = parser.parse_args()
|
65 |
+
random.seed(args.seed)
|
66 |
+
torch.random.manual_seed(args.seed)
|
67 |
+
main(args)
|
quip-sharp/eval_zeroshot.py
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import json
|
3 |
+
import argparse
|
4 |
+
import torch
|
5 |
+
import datasets
|
6 |
+
from transformers import AutoTokenizer
|
7 |
+
import random
|
8 |
+
import glog
|
9 |
+
|
10 |
+
from lib.utils import LMEvalAdaptor
|
11 |
+
from lib.utils.unsafe_import import model_from_hf_path
|
12 |
+
from lm_eval import evaluator, tasks
|
13 |
+
|
14 |
+
parser = argparse.ArgumentParser()
|
15 |
+
parser.add_argument('--seed', default=0, type=int)
|
16 |
+
parser.add_argument('--hf_path', default='hfized/quantized_hada_70b', type=str)
|
17 |
+
parser.add_argument('--batch_size', type=int, default=1, help='batch size')
|
18 |
+
parser.add_argument("--tasks", type=str)
|
19 |
+
parser.add_argument("--output_path", default=None, type=str)
|
20 |
+
parser.add_argument('--num_fewshot', type=int, default=0)
|
21 |
+
parser.add_argument('--no_use_cuda_graph', action='store_true')
|
22 |
+
parser.add_argument('--no_use_flash_attn', action='store_true')
|
23 |
+
|
24 |
+
|
25 |
+
def main(args):
|
26 |
+
model, model_str = model_from_hf_path(args.hf_path,
|
27 |
+
use_cuda_graph=False,
|
28 |
+
use_flash_attn=not args.no_use_flash_attn)
|
29 |
+
tokenizer = AutoTokenizer.from_pretrained(model_str)
|
30 |
+
|
31 |
+
glog.info('loaded model!')
|
32 |
+
tokenizer.pad_token = tokenizer.eos_token
|
33 |
+
|
34 |
+
task_names = args.tasks.split(",")
|
35 |
+
|
36 |
+
lm_eval_model = LMEvalAdaptor(model_str, model, tokenizer, args.batch_size)
|
37 |
+
results = evaluator.simple_evaluate(
|
38 |
+
model=lm_eval_model,
|
39 |
+
tasks=task_names,
|
40 |
+
batch_size=args.batch_size,
|
41 |
+
no_cache=True,
|
42 |
+
num_fewshot=args.num_fewshot,
|
43 |
+
)
|
44 |
+
|
45 |
+
print(evaluator.make_table(results))
|
46 |
+
|
47 |
+
if args.output_path is not None:
|
48 |
+
os.makedirs(os.path.dirname(args.output_path), exist_ok=True)
|
49 |
+
# otherwise cannot save
|
50 |
+
results["config"]["model"] = args.hf_path
|
51 |
+
with open(args.output_path, "w") as f:
|
52 |
+
json.dump(results, f, indent=2)
|
53 |
+
|
54 |
+
|
55 |
+
if __name__ == '__main__':
|
56 |
+
torch.set_grad_enabled(False)
|
57 |
+
args = parser.parse_args()
|
58 |
+
random.seed(args.seed)
|
59 |
+
torch.random.manual_seed(args.seed)
|
60 |
+
main(args)
|
quip-sharp/gen_speed.py
ADDED
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import os
|
3 |
+
import glog
|
4 |
+
import torch
|
5 |
+
from torch.profiler import profile, record_function, ProfilerActivity
|
6 |
+
from transformers import AutoTokenizer
|
7 |
+
from lib.utils.unsafe_import import model_from_hf_path
|
8 |
+
import time
|
9 |
+
|
10 |
+
torch.set_grad_enabled(False)
|
11 |
+
|
12 |
+
parser = argparse.ArgumentParser()
|
13 |
+
parser.add_argument('--hf_path', default='meta-llama/Llama-2-70b-hf', type=str)
|
14 |
+
parser.add_argument('--batch_size', default=1, type=int)
|
15 |
+
parser.add_argument('--seqlen', default=1, type=int)
|
16 |
+
parser.add_argument('--samples', default=100, type=int)
|
17 |
+
parser.add_argument('--no_use_cuda_graph', action='store_true')
|
18 |
+
parser.add_argument('--no_use_flash_attn', action='store_true')
|
19 |
+
|
20 |
+
|
21 |
+
def main(args):
|
22 |
+
model, model_str = model_from_hf_path(args.hf_path,
|
23 |
+
use_cuda_graph=not args.no_use_cuda_graph,
|
24 |
+
use_flash_attn=not args.no_use_flash_attn)
|
25 |
+
tokenizer = AutoTokenizer.from_pretrained(model_str)
|
26 |
+
|
27 |
+
prompt = 'It is a truth universally acknowledged that'
|
28 |
+
inputs = tokenizer(prompt, return_tensors='pt')
|
29 |
+
token = inputs['input_ids'][0:1, 0:1].cuda().repeat(args.batch_size, args.seqlen)
|
30 |
+
model(token, use_cache=False)
|
31 |
+
|
32 |
+
torch.cuda.synchronize()
|
33 |
+
start = time.time()
|
34 |
+
for _ in range(args.samples):
|
35 |
+
model(token, use_cache=False)
|
36 |
+
torch.cuda.synchronize()
|
37 |
+
end = time.time()
|
38 |
+
print('TIME', (end - start) / args.samples)
|
39 |
+
|
40 |
+
|
41 |
+
if __name__ == '__main__':
|
42 |
+
torch.set_grad_enabled(False)
|
43 |
+
torch.manual_seed(0)
|
44 |
+
args = parser.parse_args()
|
45 |
+
main(args)
|
quip-sharp/hessian_offline_llama.py
ADDED
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import datetime
|
3 |
+
import random
|
4 |
+
import argparse
|
5 |
+
from copy import deepcopy
|
6 |
+
from tqdm import tqdm
|
7 |
+
|
8 |
+
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "max_split_size_mb:512"
|
9 |
+
|
10 |
+
import numpy
|
11 |
+
import torch
|
12 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, PreTrainedTokenizerFast
|
13 |
+
from datasets import load_dataset
|
14 |
+
|
15 |
+
import torch.multiprocessing as mp
|
16 |
+
|
17 |
+
# import data_utils
|
18 |
+
from lib import utils
|
19 |
+
|
20 |
+
parser = argparse.ArgumentParser()
|
21 |
+
parser.add_argument('--seed', default=0, type=int)
|
22 |
+
parser.add_argument('--batch_size', default=2, type=int)
|
23 |
+
parser.add_argument('--devset_size', default=256, type=int)
|
24 |
+
parser.add_argument('--ctx_size', default=4096, type=int)
|
25 |
+
parser.add_argument('--base_model', default='meta-llama/Llama-2-70b-hf', type=str)
|
26 |
+
parser.add_argument('--save_path', default='hessians/llama2_70b', type=str)
|
27 |
+
parser.add_argument('--scratch_path', default=None, type=str)
|
28 |
+
parser.add_argument('--chunk_size', default=256, type=int)
|
29 |
+
parser.add_argument('--async_copy_speed', default=-1, type=int)
|
30 |
+
parser.add_argument('--act_save_rate', default=4, type=int)
|
31 |
+
parser.add_argument('--save_activations', action='store_true')
|
32 |
+
parser.add_argument('--sample_proc', default=4, type=int)
|
33 |
+
|
34 |
+
|
35 |
+
def move_fn(in_q, async_copy_speed):
|
36 |
+
# async copy to avoid slow disk
|
37 |
+
while True:
|
38 |
+
item = in_q.get()
|
39 |
+
if item is None:
|
40 |
+
return
|
41 |
+
src, tgt = item
|
42 |
+
if async_copy_speed > 0:
|
43 |
+
os.system(f'rsync --bwlimit={async_copy_speed} {src} {tgt}')
|
44 |
+
else:
|
45 |
+
os.system(f'rsync {src} {tgt}')
|
46 |
+
os.system(f'rm {src}')
|
47 |
+
print(f'moved {src} to {tgt}')
|
48 |
+
|
49 |
+
|
50 |
+
def forward_layer(layer, position_ids, attention_mask, bs, device, in_q, out_q):
|
51 |
+
torch.set_grad_enabled(False)
|
52 |
+
layer = layer.to(device)
|
53 |
+
position_ids = position_ids.to(device)
|
54 |
+
attention_mask = attention_mask.to(device)
|
55 |
+
done_qkv = utils.register_H_hook(layer.self_attn.q_proj, device)
|
56 |
+
done_o = utils.register_H_hook(layer.self_attn.o_proj, device)
|
57 |
+
done_up = utils.register_H_hook(layer.mlp.up_proj, device)
|
58 |
+
done_down = utils.register_H_hook(layer.mlp.down_proj, device)
|
59 |
+
|
60 |
+
while True:
|
61 |
+
dev_emb = in_q.get()
|
62 |
+
if dev_emb is None:
|
63 |
+
layer = layer.cpu()
|
64 |
+
position_ids = position_ids.cpu()
|
65 |
+
attention_mask = attention_mask.cpu()
|
66 |
+
out_q.put({'qkv': done_qkv(), 'o': done_o(), 'up': done_up(), 'down': done_down()})
|
67 |
+
return
|
68 |
+
|
69 |
+
assert len(dev_emb) % bs == 0
|
70 |
+
for i in range(len(dev_emb) // bs):
|
71 |
+
dev_emb[i * bs:(i + 1) * bs] = layer(dev_emb[i * bs:(i + 1) * bs].to(device),
|
72 |
+
position_ids=position_ids,
|
73 |
+
attention_mask=attention_mask,
|
74 |
+
use_cache=False,
|
75 |
+
output_attentions=False)[0].cpu()
|
76 |
+
|
77 |
+
|
78 |
+
def accumulate(in_q, move_q, ngpus, args, transformer_layer_index):
|
79 |
+
Hs = {}
|
80 |
+
mus = {}
|
81 |
+
cts = {}
|
82 |
+
|
83 |
+
for i in range(ngpus):
|
84 |
+
out = in_q.get()
|
85 |
+
if i == 0:
|
86 |
+
for key in out:
|
87 |
+
Hs[key] = torch.zeros(out[key][0].shape, dtype=out[key][0].dtype)
|
88 |
+
mus[key] = torch.zeros(out[key][1].shape, dtype=out[key][1].dtype)
|
89 |
+
cts[key] = 0
|
90 |
+
for key in out:
|
91 |
+
Hs[key].add_(out[key][0])
|
92 |
+
mus[key].add_(out[key][1])
|
93 |
+
cts[key] += out[key][2]
|
94 |
+
|
95 |
+
keys = list(Hs.keys())
|
96 |
+
|
97 |
+
for key in Hs:
|
98 |
+
mus[key].div_(cts[key])
|
99 |
+
Hs[key].div_(cts[key])
|
100 |
+
Hs[key].addmm_(-mus[key].unsqueeze(-1), mus[key].unsqueeze(0))
|
101 |
+
save_path = f"{args.scratch_path}/{transformer_layer_index}_{key}.pt" if args.scratch_path is not None else f"{args.save_path}/{transformer_layer_index}_{key}.pt"
|
102 |
+
torch.save(
|
103 |
+
{
|
104 |
+
'flatH': utils.sym_to_flat(Hs[key].to(torch.float32)),
|
105 |
+
'mu': mus[key].to(torch.float32),
|
106 |
+
'n': Hs[key].shape[0],
|
107 |
+
'ct': cts[key]
|
108 |
+
}, save_path)
|
109 |
+
if args.scratch_path is not None:
|
110 |
+
move_q.put((f"{args.scratch_path}/{transformer_layer_index}_{key}.pt",
|
111 |
+
f"{args.save_path}/{transformer_layer_index}_{key}.pt"))
|
112 |
+
|
113 |
+
del Hs, mus, cts, out
|
114 |
+
|
115 |
+
|
116 |
+
def main(args):
|
117 |
+
print("loading model...")
|
118 |
+
model = AutoModelForCausalLM.from_pretrained(args.base_model,
|
119 |
+
torch_dtype="auto",
|
120 |
+
low_cpu_mem_usage=True)
|
121 |
+
print("loaded model!")
|
122 |
+
tokenizer = AutoTokenizer.from_pretrained(args.base_model, use_fast=True)
|
123 |
+
tokenizer.pad_token = tokenizer.eos_token
|
124 |
+
|
125 |
+
if os.path.isfile(f"{args.save_path}/dev_activations.pt"):
|
126 |
+
print("loading cached dataset...")
|
127 |
+
loaded_dev_activations = torch.load(f"{args.save_path}/dev_activations.pt")
|
128 |
+
after_layer = loaded_dev_activations['after_layer']
|
129 |
+
dev_emb = loaded_dev_activations['dev_emb']
|
130 |
+
print(f"loaded cached dataset from {loaded_dev_activations['timestamp']}")
|
131 |
+
else:
|
132 |
+
print("loading dataset...")
|
133 |
+
dataset = load_dataset("togethercomputer/RedPajama-Data-1T-Sample", split="train")
|
134 |
+
devset = utils.sample_devset(dataset,
|
135 |
+
tokenizer,
|
136 |
+
args.devset_size,
|
137 |
+
args.ctx_size,
|
138 |
+
nproc=args.sample_proc)
|
139 |
+
dev_emb = model.model.embed_tokens(devset)
|
140 |
+
after_layer = -1
|
141 |
+
print("loaded dataset!")
|
142 |
+
|
143 |
+
print(f"dev_emb dtype: {dev_emb.dtype}")
|
144 |
+
dev_emb.share_memory_()
|
145 |
+
|
146 |
+
position_ids = torch.arange(args.ctx_size, dtype=torch.int64)[None, :] + \
|
147 |
+
torch.zeros(args.batch_size, args.ctx_size, dtype=torch.int64)
|
148 |
+
if hasattr(model.config, 'sliding_window'):
|
149 |
+
# mistral models
|
150 |
+
attention_mask = model.model._prepare_decoder_attention_mask(
|
151 |
+
torch.ones(args.batch_size, args.ctx_size,
|
152 |
+
dtype=torch.bool), (args.batch_size, args.ctx_size),
|
153 |
+
dev_emb[0:args.batch_size, :, :],
|
154 |
+
0,
|
155 |
+
sliding_window=model.config.sliding_window)
|
156 |
+
else:
|
157 |
+
attention_mask = model.model._prepare_decoder_attention_mask(
|
158 |
+
torch.ones(args.batch_size, args.ctx_size, dtype=torch.bool),
|
159 |
+
(args.batch_size, args.ctx_size), dev_emb[0:args.batch_size, :, :], 0)
|
160 |
+
|
161 |
+
if args.scratch_path is not None:
|
162 |
+
move_q = mp.Queue()
|
163 |
+
move_p = mp.Process(target=move_fn, args=(move_q, args.async_copy_speed))
|
164 |
+
move_p.start()
|
165 |
+
else:
|
166 |
+
move_q = None
|
167 |
+
|
168 |
+
for transformer_layer_index in range(len(model.model.layers)):
|
169 |
+
if (transformer_layer_index <= after_layer):
|
170 |
+
print(
|
171 |
+
f"skipping layer {transformer_layer_index} because it is before cached activations at layer {after_layer}"
|
172 |
+
)
|
173 |
+
continue
|
174 |
+
|
175 |
+
transformer_layer = model.model.layers[transformer_layer_index]
|
176 |
+
# check that there are four layers, as expected
|
177 |
+
assert (len([m for m in transformer_layer.modules()
|
178 |
+
if isinstance(m, torch.nn.Linear)]) == 7)
|
179 |
+
|
180 |
+
chunk_size = min(args.chunk_size, len(dev_emb))
|
181 |
+
ngpus = min(torch.cuda.device_count(), len(dev_emb) // chunk_size)
|
182 |
+
|
183 |
+
manager = mp.get_context('spawn').Manager()
|
184 |
+
in_q = manager.Queue()
|
185 |
+
out_q = manager.Queue()
|
186 |
+
|
187 |
+
accumulate_proc = mp.Process(target=accumulate,
|
188 |
+
args=(out_q, move_q, ngpus, args, transformer_layer_index))
|
189 |
+
accumulate_proc.start()
|
190 |
+
|
191 |
+
forward_procs = []
|
192 |
+
for i in range(ngpus):
|
193 |
+
p = mp.Process(target=forward_layer,
|
194 |
+
args=(transformer_layer, position_ids, attention_mask, args.batch_size,
|
195 |
+
i, in_q, out_q))
|
196 |
+
p.start()
|
197 |
+
forward_procs.append(p)
|
198 |
+
|
199 |
+
assert len(dev_emb) % args.batch_size == 0 and chunk_size % args.batch_size == 0
|
200 |
+
i = 0
|
201 |
+
while i < len(dev_emb):
|
202 |
+
next = min(i + chunk_size, len(dev_emb))
|
203 |
+
in_q.put(dev_emb[i:next])
|
204 |
+
i = next
|
205 |
+
|
206 |
+
for i in range(ngpus):
|
207 |
+
in_q.put(None)
|
208 |
+
|
209 |
+
for p in forward_procs:
|
210 |
+
p.join()
|
211 |
+
|
212 |
+
accumulate_proc.join()
|
213 |
+
|
214 |
+
transformer_layer.cpu()
|
215 |
+
model.model.layers[transformer_layer_index] = None
|
216 |
+
utils.clean()
|
217 |
+
|
218 |
+
if args.save_activations and (
|
219 |
+
transformer_layer_index % args.act_save_rate == 0 or \
|
220 |
+
transformer_layer_index == len(model.model.layers) - 1):
|
221 |
+
if args.scratch_path is not None:
|
222 |
+
if os.path.exists(f'{args.scratch_path}/dev_activations.pt'):
|
223 |
+
print('not saving layer since disk is too slow')
|
224 |
+
else:
|
225 |
+
torch.save(
|
226 |
+
{
|
227 |
+
'dev_emb': dev_emb,
|
228 |
+
'after_layer': transformer_layer_index,
|
229 |
+
'timestamp': str(datetime.datetime.now())
|
230 |
+
}, f'{args.scratch_path}/dev_activations.pt')
|
231 |
+
move_q.put((f'{args.scratch_path}/dev_activations.pt',
|
232 |
+
f'{args.save_path}/dev_activations.pt'))
|
233 |
+
else:
|
234 |
+
torch.save(
|
235 |
+
{
|
236 |
+
'dev_emb': dev_emb,
|
237 |
+
'after_layer': transformer_layer_index,
|
238 |
+
'timestamp': str(datetime.datetime.now())
|
239 |
+
}, f'{args.save_path}/dev_activations.pt')
|
240 |
+
|
241 |
+
print(f"done processing layer {transformer_layer_index}")
|
242 |
+
|
243 |
+
if args.scratch_path is not None:
|
244 |
+
move_q.put(None)
|
245 |
+
move_p.join()
|
246 |
+
|
247 |
+
|
248 |
+
if __name__ == "__main__":
|
249 |
+
mp.set_start_method('spawn')
|
250 |
+
torch.set_grad_enabled(False)
|
251 |
+
args = parser.parse_args()
|
252 |
+
torch.manual_seed(args.seed)
|
253 |
+
random.seed(args.seed)
|
254 |
+
numpy.random.seed(args.seed)
|
255 |
+
os.makedirs(args.save_path, exist_ok=True)
|
256 |
+
main(args)
|
quip-sharp/hfize_llama.py
ADDED
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import os
|
3 |
+
import glog
|
4 |
+
import torch
|
5 |
+
from transformers import AutoTokenizer
|
6 |
+
from model.version import MODEL_VERSION
|
7 |
+
from model.llama import LlamaForCausalLM as llama_fuse
|
8 |
+
from model.llama_nofuse import LlamaForCausalLM as llama_nofuse
|
9 |
+
from model.mistral import MistralForCausalLM
|
10 |
+
from lib import codebook
|
11 |
+
from lib.utils.unsafe_import import model_from_hf_path
|
12 |
+
import time
|
13 |
+
|
14 |
+
torch.set_grad_enabled(False)
|
15 |
+
|
16 |
+
parser = argparse.ArgumentParser()
|
17 |
+
parser.add_argument('--quantized_path', type=str)
|
18 |
+
parser.add_argument('--hf_output_path', type=str)
|
19 |
+
|
20 |
+
|
21 |
+
def unpack_quip(module, saved_layer, codebook_id, codesz):
|
22 |
+
(m, n) = saved_layer['Qidxs'].shape
|
23 |
+
if codebook_id in codebook.cache_permute_set:
|
24 |
+
module.Qidxs.copy_(saved_layer['Qidxs'].view(m, n // codesz,
|
25 |
+
codesz).permute(1, 0,
|
26 |
+
2).reshape(m, n).contiguous())
|
27 |
+
else:
|
28 |
+
module.Qidxs.copy_(saved_layer['Qidxs'])
|
29 |
+
|
30 |
+
if module.rank > 0:
|
31 |
+
module.A.copy_(saved_layer['A'])
|
32 |
+
module.B.copy_(saved_layer['B'])
|
33 |
+
module.SU.copy_(saved_layer['SU'])
|
34 |
+
module.SV.copy_(saved_layer['SV'])
|
35 |
+
module.Wscale.copy_(saved_layer['Wscale'])
|
36 |
+
if module.rescale_WH:
|
37 |
+
module.scaleWH.copy_(saved_layer['scaleWH'])
|
38 |
+
|
39 |
+
module.codebook_id.copy_(codebook_id)
|
40 |
+
|
41 |
+
|
42 |
+
def main(args):
|
43 |
+
assert os.path.exists(args.quantized_path)
|
44 |
+
saved_config = torch.load(os.path.join(args.quantized_path, 'config.pt'))
|
45 |
+
model_config = saved_config['model_config']
|
46 |
+
|
47 |
+
codebook_id = codebook.get_id(model_config.quip_params['codebook'])
|
48 |
+
codesz = model_config.quip_params['codesz']
|
49 |
+
|
50 |
+
tokenizer = AutoTokenizer.from_pretrained(model_config._name_or_path)
|
51 |
+
|
52 |
+
model_type = model_config.model_type
|
53 |
+
fused = model_config.quip_params.get('fused', True)
|
54 |
+
model_config.quip_params['model_version'] = MODEL_VERSION
|
55 |
+
|
56 |
+
if model_type == 'llama':
|
57 |
+
model_cls = llama_fuse if fused else llama_nofuse
|
58 |
+
elif model_type == 'mistral':
|
59 |
+
model_cls = MistralForCausalLM
|
60 |
+
else:
|
61 |
+
raise Exception
|
62 |
+
|
63 |
+
model = model_cls.from_pretrained(model_config._name_or_path,
|
64 |
+
torch_dtype='auto',
|
65 |
+
low_cpu_mem_usage=True,
|
66 |
+
config=model_config).half()
|
67 |
+
|
68 |
+
for ii in range(len(model.model.layers)):
|
69 |
+
glog.info(f'updating layer {ii}')
|
70 |
+
|
71 |
+
layer = model.model.layers[ii]
|
72 |
+
cpu = torch.device('cpu')
|
73 |
+
|
74 |
+
if fused:
|
75 |
+
glog.info(f'loading layer {ii} qkv')
|
76 |
+
saved_layer = torch.load(f'{args.quantized_path}/{ii}_qkv.pt', map_location=cpu)
|
77 |
+
layer.self_attn.q_scale.copy_(saved_layer['W_q_scale'])
|
78 |
+
layer.self_attn.k_scale.copy_(saved_layer['W_k_scale'])
|
79 |
+
layer.self_attn.v_scale.copy_(saved_layer['W_v_scale'])
|
80 |
+
unpack_quip(layer.self_attn.qkv_proj, saved_layer, codebook_id, codesz)
|
81 |
+
|
82 |
+
glog.info(f'loading layer {ii} up')
|
83 |
+
saved_layer = torch.load(f'{args.quantized_path}/{ii}_up.pt', map_location=cpu)
|
84 |
+
layer.mlp.up_scale.copy_(saved_layer['W_up_scale'])
|
85 |
+
layer.mlp.gate_scale.copy_(saved_layer['W_gate_scale'])
|
86 |
+
unpack_quip(layer.mlp.upgate_proj, saved_layer, codebook_id, codesz)
|
87 |
+
|
88 |
+
glog.info(f'loading layer {ii} o')
|
89 |
+
saved_layer = torch.load(f'{args.quantized_path}/{ii}_o.pt', map_location=cpu)
|
90 |
+
layer.self_attn.o_scale.copy_(saved_layer['W_o_scale'])
|
91 |
+
unpack_quip(layer.self_attn.o_proj, saved_layer, codebook_id, codesz)
|
92 |
+
|
93 |
+
glog.info(f'loading layer {ii} down')
|
94 |
+
saved_layer = torch.load(f'{args.quantized_path}/{ii}_down.pt', map_location=cpu)
|
95 |
+
layer.mlp.down_scale.copy_(saved_layer['W_down_scale'])
|
96 |
+
|
97 |
+
if model_config.quip_params['outlier_channel_split']:
|
98 |
+
layer.mlp.down_proj.ocs_dupe_inds.copy_(torch.tensor(saved_layer['ocs_dupe_inds']))
|
99 |
+
|
100 |
+
unpack_quip(layer.mlp.down_proj, saved_layer, codebook_id, codesz)
|
101 |
+
|
102 |
+
else:
|
103 |
+
saved_layer = torch.load(f'{args.quantized_path}/{ii}_q.pt', map_location=cpu)
|
104 |
+
layer.self_attn.q_scale.copy_(saved_layer['W_scale'])
|
105 |
+
if model_config.quip_params['outlier_channel_split']:
|
106 |
+
layer.self_attn.q_proj.ocs_dupe_inds.copy_(
|
107 |
+
torch.tensor(saved_layer['ocs_dupe_inds']))
|
108 |
+
unpack_quip(layer.self_attn.q_proj, saved_layer, codebook_id, codesz)
|
109 |
+
|
110 |
+
saved_layer = torch.load(f'{args.quantized_path}/{ii}_k.pt', map_location=cpu)
|
111 |
+
layer.self_attn.k_scale.copy_(saved_layer['W_scale'])
|
112 |
+
if model_config.quip_params['outlier_channel_split']:
|
113 |
+
layer.self_attn.k_proj.ocs_dupe_inds.copy_(
|
114 |
+
torch.tensor(saved_layer['ocs_dupe_inds']))
|
115 |
+
unpack_quip(layer.self_attn.k_proj, saved_layer, codebook_id, codesz)
|
116 |
+
|
117 |
+
saved_layer = torch.load(f'{args.quantized_path}/{ii}_v.pt', map_location=cpu)
|
118 |
+
layer.self_attn.v_scale.copy_(saved_layer['W_scale'])
|
119 |
+
if model_config.quip_params['outlier_channel_split']:
|
120 |
+
layer.self_attn.v_proj.ocs_dupe_inds.copy_(
|
121 |
+
torch.tensor(saved_layer['ocs_dupe_inds']))
|
122 |
+
unpack_quip(layer.self_attn.v_proj, saved_layer, codebook_id, codesz)
|
123 |
+
|
124 |
+
saved_layer = torch.load(f'{args.quantized_path}/{ii}_o.pt', map_location=cpu)
|
125 |
+
layer.self_attn.o_scale.copy_(saved_layer['W_scale'])
|
126 |
+
if model_config.quip_params['outlier_channel_split']:
|
127 |
+
layer.self_attn.o_proj.ocs_dupe_inds.copy_(
|
128 |
+
torch.tensor(saved_layer['ocs_dupe_inds']))
|
129 |
+
unpack_quip(layer.self_attn.o_proj, saved_layer, codebook_id, codesz)
|
130 |
+
|
131 |
+
saved_layer = torch.load(f'{args.quantized_path}/{ii}_up.pt', map_location=cpu)
|
132 |
+
layer.mlp.up_scale.copy_(saved_layer['W_scale'])
|
133 |
+
if model_config.quip_params['outlier_channel_split']:
|
134 |
+
layer.mlp.up_proj.ocs_dupe_inds.copy_(torch.tensor(saved_layer['ocs_dupe_inds']))
|
135 |
+
unpack_quip(layer.mlp.up_proj, saved_layer, codebook_id, codesz)
|
136 |
+
|
137 |
+
saved_layer = torch.load(f'{args.quantized_path}/{ii}_gate.pt', map_location=cpu)
|
138 |
+
layer.mlp.gate_scale.copy_(saved_layer['W_scale'])
|
139 |
+
if model_config.quip_params['outlier_channel_split']:
|
140 |
+
layer.mlp.gate_proj.ocs_dupe_inds.copy_(torch.tensor(saved_layer['ocs_dupe_inds']))
|
141 |
+
unpack_quip(layer.mlp.gate_proj, saved_layer, codebook_id, codesz)
|
142 |
+
|
143 |
+
saved_layer = torch.load(f'{args.quantized_path}/{ii}_down.pt', map_location=cpu)
|
144 |
+
layer.mlp.down_scale.copy_(saved_layer['W_scale'])
|
145 |
+
if model_config.quip_params['outlier_channel_split']:
|
146 |
+
layer.mlp.down_proj.ocs_dupe_inds.copy_(torch.tensor(saved_layer['ocs_dupe_inds']))
|
147 |
+
unpack_quip(layer.mlp.down_proj, saved_layer, codebook_id, codesz)
|
148 |
+
|
149 |
+
glog.info(f'saving model...')
|
150 |
+
model.save_pretrained(args.hf_output_path, safe_serialization=True)
|
151 |
+
|
152 |
+
del model
|
153 |
+
|
154 |
+
model, _ = model_from_hf_path(args.hf_output_path, use_cuda_graph=False)
|
155 |
+
|
156 |
+
glog.info('successfully loaded hfized model')
|
157 |
+
|
158 |
+
glog.info('generating some text...')
|
159 |
+
|
160 |
+
start = time.time()
|
161 |
+
prompt = 'It is a truth universally acknowledged that'
|
162 |
+
inputs = tokenizer(prompt, return_tensors='pt')
|
163 |
+
outputs = model.generate(input_ids=inputs['input_ids'].cuda(),
|
164 |
+
attention_mask=inputs['attention_mask'].cuda(),
|
165 |
+
max_new_tokens=64,
|
166 |
+
return_dict_in_generate=True)
|
167 |
+
token = outputs.sequences[0, :]
|
168 |
+
output_str = tokenizer.decode(token)
|
169 |
+
glog.info(output_str)
|
170 |
+
glog.info(f'elapsed: {time.time() - start}')
|
171 |
+
|
172 |
+
|
173 |
+
if __name__ == '__main__':
|
174 |
+
torch.set_grad_enabled(False)
|
175 |
+
torch.manual_seed(0)
|
176 |
+
args = parser.parse_args()
|
177 |
+
main(args)
|
quip-sharp/interactive_gen.py
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import os
|
3 |
+
import glog
|
4 |
+
import torch
|
5 |
+
from torch.profiler import profile, record_function, ProfilerActivity
|
6 |
+
from transformers import AutoTokenizer
|
7 |
+
from lib.utils.unsafe_import import model_from_hf_path
|
8 |
+
import time
|
9 |
+
|
10 |
+
torch.set_grad_enabled(False)
|
11 |
+
|
12 |
+
parser = argparse.ArgumentParser()
|
13 |
+
parser.add_argument('--hf_path', default='meta-llama/Llama-2-70b-hf', type=str)
|
14 |
+
parser.add_argument('--max_length', default=64, type=int)
|
15 |
+
parser.add_argument('--no_use_flash_attn', action='store_true')
|
16 |
+
|
17 |
+
|
18 |
+
def main(args):
|
19 |
+
model, model_str = model_from_hf_path(args.hf_path,
|
20 |
+
use_cuda_graph=False,
|
21 |
+
use_flash_attn=not args.no_use_flash_attn)
|
22 |
+
tokenizer = AutoTokenizer.from_pretrained(model_str)
|
23 |
+
tokenizer.pad_token = tokenizer.eos_token
|
24 |
+
|
25 |
+
while True:
|
26 |
+
print()
|
27 |
+
prompt = input("Please enter your prompt or 'quit' (without quotes) to quit: ")
|
28 |
+
if prompt == 'quit':
|
29 |
+
return
|
30 |
+
inputs = tokenizer(prompt, return_tensors='pt')
|
31 |
+
outputs = model.generate(input_ids=inputs['input_ids'].cuda(),
|
32 |
+
attention_mask=inputs['attention_mask'].cuda(),
|
33 |
+
max_length=args.max_length,
|
34 |
+
penalty_alpha=0.6,
|
35 |
+
top_k=4,
|
36 |
+
use_cache=True,
|
37 |
+
return_dict_in_generate=True).sequences[0]
|
38 |
+
print()
|
39 |
+
print('Model Output: ', tokenizer.decode(outputs, skip_special_tokens=True))
|
40 |
+
|
41 |
+
|
42 |
+
if __name__ == '__main__':
|
43 |
+
torch.set_grad_enabled(False)
|
44 |
+
torch.manual_seed(0)
|
45 |
+
args = parser.parse_args()
|
46 |
+
main(args)
|
quip-sharp/lib/__init__.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
|
quip-sharp/lib/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (173 Bytes). View file
|
|
quip-sharp/lib/__pycache__/__init__.cpython-39.pyc
ADDED
Binary file (128 Bytes). View file
|
|
quip-sharp/lib/algo/__init__.py
ADDED
File without changes
|
quip-sharp/lib/algo/__pycache__/__init__.cpython-39.pyc
ADDED
Binary file (133 Bytes). View file
|
|
quip-sharp/lib/algo/__pycache__/outlier_channel_split.cpython-39.pyc
ADDED
Binary file (1.48 kB). View file
|
|
quip-sharp/lib/algo/__pycache__/preprocess.cpython-39.pyc
ADDED
Binary file (452 Bytes). View file
|
|
quip-sharp/lib/algo/__pycache__/quip.cpython-39.pyc
ADDED
Binary file (10.7 kB). View file
|
|
quip-sharp/lib/algo/outlier_channel_split.py
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from tqdm import tqdm
|
3 |
+
import math
|
4 |
+
|
5 |
+
|
6 |
+
def outlier_channel_split(W, H, mu, to_size):
|
7 |
+
old_dim = W.shape[-1]
|
8 |
+
remaining = to_size - old_dim
|
9 |
+
|
10 |
+
W = torch.cat([W, torch.zeros(W.shape[0], remaining).to(W.device)], dim=-1)
|
11 |
+
new_H = torch.zeros(to_size, to_size).to(H.device)
|
12 |
+
new_H[0:H.shape[0], 0:H.shape[1]] = H
|
13 |
+
H = new_H
|
14 |
+
mu = torch.cat([mu, torch.zeros(remaining).to(mu.device)], dim=0)
|
15 |
+
|
16 |
+
print('old drange', torch.max(W.flatten()) - torch.min(W.flatten()))
|
17 |
+
extra_inds = []
|
18 |
+
dupe_inds = list(range(old_dim))
|
19 |
+
for i in tqdm(range(old_dim, to_size), desc='outlier channel splitting'):
|
20 |
+
col = torch.argmax(W.abs()).item() % W.shape[-1]
|
21 |
+
row = math.ceil(torch.argmax(W.abs()).item() // W.shape[-1])
|
22 |
+
assert torch.allclose(W[row, col].abs(), torch.max(W.abs().flatten()))
|
23 |
+
extra_inds.append(col)
|
24 |
+
dupe_inds.append(dupe_inds[col])
|
25 |
+
W[:, col] /= 2
|
26 |
+
W[:, i] = W[:, col]
|
27 |
+
H[i, 0:i] = H[col, 0:i]
|
28 |
+
H[0:i, i] = H[0:i, col]
|
29 |
+
H[i, i] = H[col, col]
|
30 |
+
mu[i] = mu[col]
|
31 |
+
i += 1
|
32 |
+
|
33 |
+
print('new drange', torch.max(W.flatten()) - torch.min(W.flatten()))
|
34 |
+
assert torch.allclose(H.cpu(), H.cpu().T)
|
35 |
+
return W, H, mu, extra_inds, dupe_inds
|
36 |
+
|
37 |
+
|
38 |
+
def fuse_W(W, extra_inds):
|
39 |
+
for i in range(len(extra_inds)):
|
40 |
+
W[:, extra_inds[-(i + 1)]] += W[:, -(i + 1)]
|
41 |
+
return W[:, :W.shape[-1] - len(extra_inds)]
|
quip-sharp/lib/algo/preprocess.py
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from tqdm import tqdm
|
3 |
+
from lib import utils
|
4 |
+
|
5 |
+
|
6 |
+
def basic_preprocess(H, mu, n, args):
|
7 |
+
if not args.remove_mean:
|
8 |
+
H.add_(mu[None, :] * mu[:, None])
|
9 |
+
H = utils.regularize_H(H, n, args.sigma_reg)
|
10 |
+
return H, mu
|
quip-sharp/lib/algo/process.py
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from tqdm import tqdm
|
3 |
+
from lib import lattice, utils
|
4 |
+
|
5 |
+
|
6 |
+
def preprocess(H, mu, args):
|
7 |
+
if not args.remove_mean:
|
8 |
+
H.add_(mu[None, :] * mu[:, None])
|
9 |
+
H = utils.regularize_H(H, n, args.sigma_reg)
|
quip-sharp/lib/algo/quip.py
ADDED
@@ -0,0 +1,417 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from tqdm import tqdm
|
3 |
+
from lib import utils
|
4 |
+
import glog
|
5 |
+
import copy
|
6 |
+
|
7 |
+
|
8 |
+
def RHT_H(H, SU):
|
9 |
+
return utils.matmul_hadUt(utils.matmul_hadUt(H * SU).T * SU)
|
10 |
+
|
11 |
+
|
12 |
+
def RHT_W(W, SU, SV):
|
13 |
+
return utils.matmul_hadUt(utils.matmul_hadUt(W.T * SV).T * SU)
|
14 |
+
|
15 |
+
|
16 |
+
def incoherence_preprocess(H, W, args):
|
17 |
+
dtype_ = torch.float64 if args.use_fp64 else torch.float32
|
18 |
+
device = H.device
|
19 |
+
(m, n) = W.shape
|
20 |
+
|
21 |
+
def _dump(Hr, Lhr, msg=''):
|
22 |
+
torch.save(Hr, f"{args.save_pfx}/Hr_debug_fft.pt")
|
23 |
+
torch.save(Lhr, f"{args.save_pfx}/Lhr_debug_fft.pt")
|
24 |
+
raise Exception(msg)
|
25 |
+
|
26 |
+
# diagonally rescale W,H to minimize proxy loss
|
27 |
+
scaleWH = None
|
28 |
+
Wr = W
|
29 |
+
Hr = H
|
30 |
+
if args.rescale_WH:
|
31 |
+
Hr = H / H.abs().max()
|
32 |
+
diagH = torch.diag(Hr)
|
33 |
+
diagW2 = torch.diag(W.T @ W)
|
34 |
+
diagH = torch.clamp(diagH, min=1e-8)
|
35 |
+
diagW2 = torch.clamp(diagW2, min=1e-8)
|
36 |
+
scaleWH = (diagH / diagW2).sqrt().sqrt().to(torch.float32)
|
37 |
+
scaleWH = scaleWH.clamp(min=1e-8)
|
38 |
+
Wr = Wr * scaleWH[None, :]
|
39 |
+
Hr = Hr / scaleWH[None, :]
|
40 |
+
Hr = Hr / scaleWH[:, None]
|
41 |
+
scaleWH = scaleWH.cpu()
|
42 |
+
|
43 |
+
# randomized hadamard transformation on H, W
|
44 |
+
if args.incoh_mode == "had":
|
45 |
+
SU = (torch.randn(n, device=device).sign() + 1e-5).sign().to(dtype_)
|
46 |
+
SV = (torch.randn(m, device=device).sign() + 1e-5).sign().to(dtype_)
|
47 |
+
Hr = RHT_H(Hr, SU)
|
48 |
+
Wr = RHT_W(Wr, SU, SV)
|
49 |
+
# randomized kronecker product on H, W
|
50 |
+
elif args.incoh_mode == "kron":
|
51 |
+
SU = utils.rand_ortho_butterfly_noblock(n).to(dtype_).to(device)
|
52 |
+
SV = utils.rand_ortho_butterfly_noblock(m).to(dtype_).to(device)
|
53 |
+
Hr = SU @ Hr @ SU.T
|
54 |
+
Wr = SV @ Wr @ SU.T
|
55 |
+
else:
|
56 |
+
raise NotImplementedError
|
57 |
+
SV = SV.cpu()
|
58 |
+
SU = SU.cpu()
|
59 |
+
|
60 |
+
Lhr = torch.linalg.cholesky(Hr)
|
61 |
+
if not torch.all(torch.isfinite(Lhr)):
|
62 |
+
return None
|
63 |
+
|
64 |
+
Wr = Wr.to(device)
|
65 |
+
|
66 |
+
return Lhr, Hr, Wr, SU, SV, scaleWH
|
67 |
+
|
68 |
+
|
69 |
+
def incoherence_process(hatWr, SU, SV, scaleWH, args):
|
70 |
+
device = hatWr.device
|
71 |
+
# reverse hadamard transformation
|
72 |
+
if args.incoh_mode == 'had':
|
73 |
+
hatWr = (utils.matmul_hadU((utils.matmul_hadU(hatWr) * SU.to(device)).T) * SV.to(device)).T
|
74 |
+
# reverse kronecker product
|
75 |
+
elif args.incoh_mode == 'kron':
|
76 |
+
hatWr = SV.T.to(device) @ hatWr @ SU.to(device)
|
77 |
+
else:
|
78 |
+
raise NotImplementedError
|
79 |
+
|
80 |
+
# reverse rescale W,H
|
81 |
+
if args.rescale_WH:
|
82 |
+
hatWr /= scaleWH[None, :].to(device)
|
83 |
+
|
84 |
+
assert torch.isfinite(hatWr).all()
|
85 |
+
return hatWr
|
86 |
+
|
87 |
+
|
88 |
+
def low_rank_preprocess(Wr, Hr, Lhr, args):
|
89 |
+
dtype_ = torch.float64 if args.use_fp64 else torch.float32
|
90 |
+
if args.full_svd:
|
91 |
+
svdZ = torch.linalg.svd(Wr.to(torch.float64) @ Lhr.to(torch.float64), full_matrices=False)
|
92 |
+
Hr -= (Lhr.to(torch.float64) @ svdZ.Vh.T[:, :args.lora_rank] @ \
|
93 |
+
svdZ.Vh[:args.lora_rank] @ Lhr.to(torch.float64).T).to(dtype_)
|
94 |
+
Hr += torch.diag(Hr).mean() * args.sigma_reg2 * \
|
95 |
+
torch.eye(Hr.shape[0], device=Hr.device, dtype=Hr.dtype)
|
96 |
+
Wr -= (svdZ.U[:, :args.lora_rank] @ svdZ.U.T[:args.lora_rank] @ Wr.to(
|
97 |
+
torch.float64)).to(dtype_)
|
98 |
+
else:
|
99 |
+
U_lrz, S_lrz, V_lrz = torch.svd_lowrank(Wr.to(torch.float64) @ Lhr.to(torch.float64),
|
100 |
+
q=2 * args.lora_rank,
|
101 |
+
niter=10)
|
102 |
+
U_lrz = U_lrz[:, :args.lora_rank]
|
103 |
+
V_lrz = V_lrz[:, :args.lora_rank]
|
104 |
+
Hr -= (Lhr.to(torch.float64) @ V_lrz @ V_lrz.T @ Lhr.to(torch.float64).T).to(dtype_)
|
105 |
+
Hr += torch.diag(Hr).mean() * args.sigma_reg2 * \
|
106 |
+
torch.eye(Hr.shape[0], device=Hr.device, dtype=Hr.dtype)
|
107 |
+
Wr -= (U_lrz @ U_lrz.T @ Wr.to(torch.float64)).to(dtype_)
|
108 |
+
return Wr, Hr
|
109 |
+
|
110 |
+
|
111 |
+
def low_rank_process(Wo, hatWr, Lhr, args):
|
112 |
+
# invLhr = torch.linalg.inv(Lhr)
|
113 |
+
# assert torch.isfinite(invLhr).all()
|
114 |
+
|
115 |
+
svdRZ = torch.linalg.svd((Wo - hatWr) @ Lhr, full_matrices=False)
|
116 |
+
A = svdRZ.U[:, :args.lora_rank]
|
117 |
+
# B = torch.diag(svdRZ.S[:args.lora_rank]) @ svdRZ.Vh[:args.lora_rank] @ invLhr
|
118 |
+
B = torch.linalg.solve_triangular(
|
119 |
+
Lhr,
|
120 |
+
torch.diag(svdRZ.S[:args.lora_rank]) @ svdRZ.Vh[:args.lora_rank],
|
121 |
+
upper=False,
|
122 |
+
left=False)
|
123 |
+
assert torch.isfinite(A).all() and torch.isfinite(B).all()
|
124 |
+
|
125 |
+
svdB = torch.linalg.svd(B, full_matrices=False)
|
126 |
+
A = (A @ svdB.U @ torch.diag(svdB.S.sqrt())).half()
|
127 |
+
B = (torch.diag(svdB.S.sqrt()) @ svdB.Vh).half()
|
128 |
+
|
129 |
+
hatWr = hatWr.to(A.device) + \
|
130 |
+
(A @ B).to(torch.float64 if args.use_fp64 else torch.float32)
|
131 |
+
return hatWr, A, B
|
132 |
+
|
133 |
+
|
134 |
+
def LDLQ(Wr, Hr, L, D, cb, args):
|
135 |
+
'''
|
136 |
+
want eta = (Wr - hatWr) @ L
|
137 |
+
want hatWr + eta = Wr + (Wr - hatWr) @ (L - I)
|
138 |
+
want hatWr = Q( Wr + (Wr - hatWr) @ (L - I) )
|
139 |
+
'''
|
140 |
+
(m, n) = Wr.shape
|
141 |
+
L, D = utils.block_LDL(Hr, cb.codesz)
|
142 |
+
hatWr = torch.zeros(m, n, dtype=Hr.dtype, device=Hr.device)
|
143 |
+
Qidxs = torch.zeros(m, n // cb.codesz, dtype=cb.idx_dtype, device=Hr.device)
|
144 |
+
for k in reversed(range(n // cb.codesz)):
|
145 |
+
WXWX = Wr[:, (cb.codesz * k):(cb.codesz * (k + 1))] + \
|
146 |
+
(Wr[:, (cb.codesz * (k + 1)):n] - hatWr[:, (cb.codesz * (k + 1)):n]) @ \
|
147 |
+
L[(cb.codesz * (k + 1)):n, (cb.codesz * k):(cb.codesz * (k + 1))]
|
148 |
+
hatWr[:, (cb.codesz * k):(cb.codesz * (k + 1))], Qidxs[:, k] = \
|
149 |
+
cb.quantize(WXWX)
|
150 |
+
for ie in range(args.quip_tune_iters):
|
151 |
+
for k in reversed(range(n // cb.codesz)):
|
152 |
+
WXWX = hatWr[:, (cb.codesz * k):(cb.codesz * (k + 1))] + (Wr - hatWr) @ \
|
153 |
+
Hr[:, (cb.codesz * k):(cb.codesz * (k + 1))] @ \
|
154 |
+
torch.linalg.inv(Hr[(cb.codesz * k):(cb.codesz * (k + 1)),
|
155 |
+
(cb.codesz * k):(cb.codesz * (k + 1))])
|
156 |
+
hatWr[:, (cb.codesz * k):(cb.codesz * (k + 1))], Qidxs[:, k] = cb.quantize(WXWX)
|
157 |
+
|
158 |
+
return hatWr, Qidxs
|
159 |
+
|
160 |
+
|
161 |
+
def LDLQ_buffered(Wr, Hr, L, D, cb, args, buf_cols=128):
|
162 |
+
'''
|
163 |
+
reduce overhead of memory r/w
|
164 |
+
buffer size is in groups of codesz (4) columns (for D4)
|
165 |
+
'''
|
166 |
+
(m, n) = Wr.shape
|
167 |
+
assert buf_cols % cb.codesz == 0
|
168 |
+
assert n % buf_cols == 0
|
169 |
+
buf_size = buf_cols // cb.codesz
|
170 |
+
|
171 |
+
L, D = utils.block_LDL(Hr, cb.codesz)
|
172 |
+
hatWr_T = torch.zeros(n, m, dtype=Hr.dtype, device=Hr.device)
|
173 |
+
Qidxs_T = torch.zeros(n // cb.codesz, m, dtype=cb.idx_dtype, device=Hr.device)
|
174 |
+
|
175 |
+
Wr_T = Wr.T.contiguous()
|
176 |
+
Wr = Wr.cpu()
|
177 |
+
Hr_T = Hr.T.contiguous()
|
178 |
+
Hr = Hr.cpu()
|
179 |
+
|
180 |
+
utils.clean()
|
181 |
+
|
182 |
+
# quip
|
183 |
+
prod_cache = torch.zeros(n, m, dtype=Wr_T.dtype, device=Wr_T.device)
|
184 |
+
for cur_col in range(n // cb.codesz, 0, -buf_size):
|
185 |
+
b_Wr_T = Wr_T[cb.codesz * (cur_col - buf_size):cb.codesz * cur_col]
|
186 |
+
b_hatWr_T = hatWr_T[cb.codesz * (cur_col - buf_size):cb.codesz * cur_col]
|
187 |
+
b_L = L[cb.codesz * (cur_col - buf_size):cb.codesz * cur_col].contiguous()
|
188 |
+
b_prod = prod_cache[cb.codesz * (cur_col - buf_size):cb.codesz * cur_col]
|
189 |
+
b_Qidxs_T = Qidxs_T[cur_col - buf_size:cur_col]
|
190 |
+
L_offset = cb.codesz * (cur_col - buf_size)
|
191 |
+
for i in reversed(range(buf_size)):
|
192 |
+
WXWX = b_Wr_T[cb.codesz * i : cb.codesz * (i + 1)] + \
|
193 |
+
b_L[cb.codesz * (i + 1):, L_offset + cb.codesz * i : L_offset + cb.codesz * (i + 1)].T @ \
|
194 |
+
(b_Wr_T[cb.codesz * (i + 1):] - b_hatWr_T[cb.codesz * (i + 1):]) + \
|
195 |
+
b_prod[cb.codesz * i : cb.codesz * (i + 1)]
|
196 |
+
q_out = cb.quantize(WXWX.T)
|
197 |
+
b_hatWr_T[cb.codesz * i:cb.codesz * (i + 1)] = q_out[0].T
|
198 |
+
b_Qidxs_T[i] = q_out[1]
|
199 |
+
|
200 |
+
prod_cache += b_L.T @ (b_Wr_T - b_hatWr_T)
|
201 |
+
hatWr_T[cb.codesz * (cur_col - buf_size):cb.codesz * cur_col] = b_hatWr_T
|
202 |
+
|
203 |
+
del b_Wr_T, b_hatWr_T, b_L, b_prod, L_offset, prod_cache
|
204 |
+
utils.clean()
|
205 |
+
|
206 |
+
# tune
|
207 |
+
for ie in range(args.quip_tune_iters):
|
208 |
+
# recompute delta to minimize errors
|
209 |
+
delta_T = Wr_T - hatWr_T
|
210 |
+
for cur_col in range(n // cb.codesz, 0, -buf_size):
|
211 |
+
b_hatWr_T = hatWr_T[cb.codesz * (cur_col - buf_size):cb.codesz * cur_col]
|
212 |
+
b_Hr_T = Hr_T[cb.codesz * (cur_col - buf_size):cb.codesz * cur_col]
|
213 |
+
b_delta_T = delta_T[cb.codesz * (cur_col - buf_size):cb.codesz * cur_col]
|
214 |
+
b_Qidxs_T = Qidxs_T[cur_col - buf_size:cur_col]
|
215 |
+
Hr_offset = cb.codesz * (cur_col - buf_size)
|
216 |
+
for i in reversed(range(buf_size)):
|
217 |
+
if cb.codesz > 1:
|
218 |
+
WXWX = b_hatWr_T[cb.codesz * i : cb.codesz * (i + 1)] + \
|
219 |
+
torch.linalg.inv(b_Hr_T[cb.codesz * i : cb.codesz * (i + 1), Hr_offset + cb.codesz * i : Hr_offset + cb.codesz * (i + 1)].T).T @ b_Hr_T[cb.codesz * i : cb.codesz * (i + 1)] @ delta_T
|
220 |
+
else:
|
221 |
+
WXWX = b_hatWr_T[cb.codesz * i : cb.codesz * (i + 1)] + \
|
222 |
+
(1/b_Hr_T[i, Hr_offset + i]) * b_Hr_T[cb.codesz * i : cb.codesz * (i + 1)] @ delta_T
|
223 |
+
b_delta_T[cb.codesz * i:cb.codesz * (i + 1)] += b_hatWr_T[cb.codesz * i:cb.codesz *
|
224 |
+
(i + 1)]
|
225 |
+
|
226 |
+
if ie < args.quip_tune_iters - 1:
|
227 |
+
b_hatWr_T[cb.codesz * i:cb.codesz * (i + 1)] = cb.quantize(WXWX.T, False).T
|
228 |
+
else:
|
229 |
+
q_out = cb.quantize(WXWX.T)
|
230 |
+
b_hatWr_T[cb.codesz * i:cb.codesz * (i + 1)] = q_out[0].T
|
231 |
+
b_Qidxs_T[i] = q_out[1]
|
232 |
+
|
233 |
+
b_delta_T[cb.codesz * i:cb.codesz * (i + 1)] -= b_hatWr_T[cb.codesz * i:cb.codesz *
|
234 |
+
(i + 1)]
|
235 |
+
hatWr_T[cb.codesz * (cur_col - buf_size):cb.codesz * cur_col] = b_hatWr_T
|
236 |
+
Qidxs_T[cur_col - buf_size:cur_col] = b_Qidxs_T
|
237 |
+
|
238 |
+
del delta_T, b_hatWr_T, b_Hr_T, b_delta_T, b_Qidxs_T, Hr_offset
|
239 |
+
utils.clean()
|
240 |
+
|
241 |
+
return hatWr_T.T.contiguous(), Qidxs_T.T.contiguous()
|
242 |
+
|
243 |
+
|
244 |
+
def LDLQ_buffered_lowmem(Wr, Hr, L, D, cb, args, buf_cols=128):
|
245 |
+
'''
|
246 |
+
reduce overhead of memory r/w
|
247 |
+
buffer size is in groups of code_col (4) columns (for D4)
|
248 |
+
'''
|
249 |
+
(m, n) = Wr.shape
|
250 |
+
hatWr = torch.zeros(m, n, dtype=Hr.dtype, device=Hr.device)
|
251 |
+
Qidxs = torch.zeros(m, n // cb.codesz, dtype=cb.idx_dtype, device=Hr.device)
|
252 |
+
assert n % buf_cols == 0 and buf_cols % cb.codesz == 0
|
253 |
+
buf_size = buf_cols // cb.codesz
|
254 |
+
|
255 |
+
# quip
|
256 |
+
prod_cache = torch.zeros(m, n, dtype=Wr.dtype, device=Wr.device)
|
257 |
+
for cur_col in range(n // cb.codesz, 0, -buf_size):
|
258 |
+
b_Wr = Wr[:, cb.codesz * (cur_col - buf_size):cb.codesz * cur_col]
|
259 |
+
b_hatWr = hatWr[:, cb.codesz * (cur_col - buf_size):cb.codesz * cur_col]
|
260 |
+
b_L = L[cb.codesz * (cur_col - buf_size):cb.codesz * cur_col]
|
261 |
+
b_prod = prod_cache[:, cb.codesz * (cur_col - buf_size):cb.codesz * cur_col]
|
262 |
+
b_Qidxs = Qidxs[:, cur_col - buf_size:cur_col]
|
263 |
+
L_offset = cb.codesz * (cur_col - buf_size)
|
264 |
+
for i in reversed(range(buf_size)):
|
265 |
+
WXWX = b_Wr[:, cb.codesz * i : cb.codesz * (i + 1)] + \
|
266 |
+
(b_Wr[:, cb.codesz * (i + 1):] - b_hatWr[:, cb.codesz * (i + 1):]) @ \
|
267 |
+
b_L[cb.codesz * (i + 1):, L_offset + cb.codesz * i : L_offset + cb.codesz * (i + 1)] + \
|
268 |
+
b_prod[:, cb.codesz * i : cb.codesz * (i + 1)]
|
269 |
+
b_hatWr[:, cb.codesz * i : cb.codesz * (i + 1)], b_Qidxs[:, i] = cb.quantize(WXWX)
|
270 |
+
prod_cache += (b_Wr - b_hatWr) @ b_L
|
271 |
+
|
272 |
+
del b_Wr, b_hatWr, b_L, b_prod, L_offset, prod_cache
|
273 |
+
utils.clean()
|
274 |
+
|
275 |
+
# tune
|
276 |
+
for ie in range(args.quip_tune_iters):
|
277 |
+
# recompute delta to minimize errors
|
278 |
+
delta = Wr - hatWr
|
279 |
+
for cur_col in range(n // cb.codesz, 0, -buf_size):
|
280 |
+
b_hatWr = hatWr[:, cb.codesz * (cur_col - buf_size):cb.codesz * cur_col]
|
281 |
+
b_Hr = Hr[:, cb.codesz * (cur_col - buf_size):cb.codesz * cur_col]
|
282 |
+
b_delta = delta[:, cb.codesz * (cur_col - buf_size):cb.codesz * cur_col]
|
283 |
+
b_Qidxs = Qidxs[:, cur_col - buf_size:cur_col]
|
284 |
+
Hr_offset = cb.codesz * (cur_col - buf_size)
|
285 |
+
for i in reversed(range(buf_size)):
|
286 |
+
if cb.codesz > 1:
|
287 |
+
inv = torch.linalg.inv(b_Hr[Hr_offset + cb.codesz * i:Hr_offset + cb.codesz *
|
288 |
+
(i + 1), cb.codesz * i:cb.codesz * (i + 1)])
|
289 |
+
else:
|
290 |
+
inv = 1 / b_Hr[Hr_offset + i:Hr_offset + i + 1, i:i + 1]
|
291 |
+
|
292 |
+
WXWX = b_hatWr[:, cb.codesz * i : cb.codesz * (i + 1)] + \
|
293 |
+
delta @ b_Hr[:, cb.codesz * i : cb.codesz * (i + 1)] @ inv
|
294 |
+
|
295 |
+
b_delta[:,
|
296 |
+
cb.codesz * i:cb.codesz * (i + 1)] += b_hatWr[:,
|
297 |
+
cb.codesz * i:cb.codesz * (i + 1)]
|
298 |
+
|
299 |
+
if ie < args.quip_tune_iters - 1:
|
300 |
+
b_hatWr[:, cb.codesz * i:cb.codesz * (i + 1)] = cb.quantize(WXWX, False)
|
301 |
+
else:
|
302 |
+
b_hatWr[:,
|
303 |
+
cb.codesz * i:cb.codesz * (i + 1)], b_Qidxs[:,
|
304 |
+
i] = cb.quantize(WXWX)
|
305 |
+
|
306 |
+
b_delta[:,
|
307 |
+
cb.codesz * i:cb.codesz * (i + 1)] -= b_hatWr[:,
|
308 |
+
cb.codesz * i:cb.codesz * (i + 1)]
|
309 |
+
del delta, b_hatWr, b_Hr, b_delta, b_Qidxs, Hr_offset
|
310 |
+
utils.clean()
|
311 |
+
|
312 |
+
return hatWr, Qidxs
|
313 |
+
|
314 |
+
|
315 |
+
def quantize(H_orig, W_orig, rank, codebook_orig, args, device='cpu'):
|
316 |
+
orig_device = H_orig.device
|
317 |
+
W_orig_dtype = W_orig.dtype
|
318 |
+
dtype_ = torch.float64 if args.use_fp64 else torch.float32
|
319 |
+
(m, n) = W_orig.shape
|
320 |
+
|
321 |
+
H = H_orig.clone().to(dtype_).to(device)
|
322 |
+
W = W_orig.clone().to(dtype_).to(device)
|
323 |
+
codebook = copy.deepcopy(codebook_orig).to(dtype_)
|
324 |
+
|
325 |
+
assert (m % 2 == 0)
|
326 |
+
assert (n % 4 == 0)
|
327 |
+
assert (torch.all(torch.isfinite(H.cpu())))
|
328 |
+
assert (torch.all(torch.isfinite(W.cpu())))
|
329 |
+
|
330 |
+
# incoherence preprocessing
|
331 |
+
incoh_out = incoherence_preprocess(H, W, args)
|
332 |
+
if incoh_out is None:
|
333 |
+
if args.use_fp64:
|
334 |
+
raise Exception
|
335 |
+
new_args = copy.deepcopy(args)
|
336 |
+
new_args.use_fp64 = True
|
337 |
+
glog.info('incoherence_preprocess failed, recomputing in fp64')
|
338 |
+
del H, W, codebook
|
339 |
+
utils.clean()
|
340 |
+
return quantize(H_orig, W_orig, rank, codebook_orig, new_args, device)
|
341 |
+
|
342 |
+
Lhr, Hr, Wr, SU, SV, scaleWH = incoh_out
|
343 |
+
del incoh_out
|
344 |
+
utils.clean()
|
345 |
+
|
346 |
+
glog.info(f'mean square of W: {W.square().mean()}')
|
347 |
+
glog.info(f'mean square of Wr: {Wr.square().mean()}')
|
348 |
+
glog.info(f'difference between Hr and Hr.T: {((Hr - Hr.T).abs().max())}')
|
349 |
+
glog.info(f'max abs of Hr: {((Hr.abs().max()))}')
|
350 |
+
glog.info(f'min diag of Lhr: {Lhr.diag().min().item()}')
|
351 |
+
|
352 |
+
Wo = Wr.clone()
|
353 |
+
|
354 |
+
# remove low rank components before LDLQ
|
355 |
+
if args.lora_rank > 0:
|
356 |
+
Wr, Hr = low_rank_preprocess(Wr, Hr, Lhr, args)
|
357 |
+
|
358 |
+
# block LDL
|
359 |
+
block_LDL_out = utils.block_LDL(Hr, codebook.codesz)
|
360 |
+
if block_LDL_out is None:
|
361 |
+
if args.use_fp64:
|
362 |
+
raise Exception
|
363 |
+
new_args = copy.deepcopy(args)
|
364 |
+
new_args.use_fp64 = True
|
365 |
+
glog.info('block_LDL failed, recomputing in fp64')
|
366 |
+
del H, W, codebook, Lhr, Hr, Wr, SU, SV, scaleWH, Wo
|
367 |
+
utils.clean()
|
368 |
+
return quantize(H_orig, W_orig, rank, codebook_orig, new_args, device)
|
369 |
+
|
370 |
+
L, D = block_LDL_out
|
371 |
+
del block_LDL_out
|
372 |
+
del H_orig, W_orig, codebook_orig
|
373 |
+
utils.clean()
|
374 |
+
|
375 |
+
# LDLQ
|
376 |
+
Wscale = Wr.square().mean().sqrt()
|
377 |
+
if args.scale_override > 0:
|
378 |
+
Wscale /= args.scale_override
|
379 |
+
else:
|
380 |
+
Wscale /= codebook.opt_scale
|
381 |
+
Wr = Wr / Wscale
|
382 |
+
codebook = codebook.to(device)
|
383 |
+
if args.no_use_buffered:
|
384 |
+
hatWr, Qidxs = LDLQ(Wr, Hr, L, D, codebook, args)
|
385 |
+
elif args.use_fp64:
|
386 |
+
hatWr, Qidxs = LDLQ_buffered_lowmem(Wr, Hr, L, D, codebook, args, buf_cols=128)
|
387 |
+
else:
|
388 |
+
hatWr, Qidxs = LDLQ_buffered(Wr, Hr, L, D, codebook, args, buf_cols=128)
|
389 |
+
|
390 |
+
hatWr = hatWr * Wscale
|
391 |
+
|
392 |
+
# low rank correction
|
393 |
+
if args.lora_rank > 0:
|
394 |
+
hatWr, A, B = low_rank_process(Wo, hatWr, Lhr, args)
|
395 |
+
A = A.half().cpu()
|
396 |
+
B = B.half().cpu()
|
397 |
+
else:
|
398 |
+
A, B = None, None
|
399 |
+
|
400 |
+
# reverse incoherence process
|
401 |
+
hatW = incoherence_process(hatWr, SU, SV, scaleWH, args)
|
402 |
+
|
403 |
+
Qidxs = codebook.maybe_pack_idxs(Qidxs)
|
404 |
+
|
405 |
+
attr = {
|
406 |
+
'Qidxs': Qidxs.to(orig_device),
|
407 |
+
'Wscale': Wscale.to(dtype_).to(orig_device),
|
408 |
+
'A': A,
|
409 |
+
'B': B,
|
410 |
+
'SU': SU.to(torch.int8).to(orig_device),
|
411 |
+
'SV': SV.to(torch.int8).to(orig_device),
|
412 |
+
'scaleWH': scaleWH,
|
413 |
+
}
|
414 |
+
|
415 |
+
utils.clean()
|
416 |
+
|
417 |
+
return hatW.to(W_orig_dtype).to(orig_device), attr
|
quip-sharp/lib/codebook/__init__.py
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from . import latticed4, latticee8_padded12, half_integer_4bit_1col
|
2 |
+
|
3 |
+
# name: (id, codebook class)
|
4 |
+
codebook_id = {
|
5 |
+
'D4': (0, latticed4.D4_codebook),
|
6 |
+
'E8P12': (7, latticee8_padded12.E8P12_codebook),
|
7 |
+
'HI4B1C': (10, half_integer_4bit_1col.HI4B1C_codebook),
|
8 |
+
}
|
9 |
+
|
10 |
+
# id from above:6quantized linear implementation
|
11 |
+
quantized_class = {
|
12 |
+
0: latticed4.QuantizedD4Linear,
|
13 |
+
7: latticee8_padded12.QuantizedE8P12Linear,
|
14 |
+
10: half_integer_4bit_1col.QuantizedHI4B1CLinear,
|
15 |
+
}
|
16 |
+
|
17 |
+
cache_permute_set = {
|
18 |
+
0, # D4
|
19 |
+
}
|
20 |
+
|
21 |
+
|
22 |
+
def get_codebook(name):
|
23 |
+
return codebook_id[name][1]()
|
24 |
+
|
25 |
+
|
26 |
+
def get_id(name):
|
27 |
+
return codebook_id[name][0]
|
28 |
+
|
29 |
+
|
30 |
+
def get_quantized_class(id):
|
31 |
+
return quantized_class[id]
|
quip-sharp/lib/codebook/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (926 Bytes). View file
|
|
quip-sharp/lib/codebook/__pycache__/__init__.cpython-39.pyc
ADDED
Binary file (881 Bytes). View file
|
|
quip-sharp/lib/codebook/__pycache__/half_integer_4bit_1col.cpython-310.pyc
ADDED
Binary file (4.1 kB). View file
|
|
quip-sharp/lib/codebook/__pycache__/half_integer_4bit_1col.cpython-39.pyc
ADDED
Binary file (4.03 kB). View file
|
|
quip-sharp/lib/codebook/__pycache__/latticed4.cpython-310.pyc
ADDED
Binary file (5.38 kB). View file
|
|
quip-sharp/lib/codebook/__pycache__/latticed4.cpython-39.pyc
ADDED
Binary file (5.34 kB). View file
|
|
quip-sharp/lib/codebook/__pycache__/latticee8_padded12.cpython-310.pyc
ADDED
Binary file (8.88 kB). View file
|
|
quip-sharp/lib/codebook/__pycache__/latticee8_padded12.cpython-39.pyc
ADDED
Binary file (8.82 kB). View file
|
|
quip-sharp/lib/codebook/half_integer_4bit_1col.py
ADDED
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from torch import nn
|
3 |
+
import quiptools_cuda
|
4 |
+
|
5 |
+
from lib.utils.matmul_had import matmul_hadU_cuda, matmul_hadUt_cuda
|
6 |
+
|
7 |
+
|
8 |
+
def get_grid():
|
9 |
+
hintr = torch.arange(-8, 8) + 1 / 2
|
10 |
+
return hintr.unsqueeze(-1)
|
11 |
+
|
12 |
+
|
13 |
+
_HI4B1C_CACHED = get_grid()
|
14 |
+
_HI4B1C_NORM_CACHED = torch.diag(_HI4B1C_CACHED @ _HI4B1C_CACHED.T)
|
15 |
+
|
16 |
+
|
17 |
+
class HI4B1C_codebook(nn.Module):
|
18 |
+
|
19 |
+
def __init__(self, inference=False):
|
20 |
+
super(HI4B1C_codebook, self).__init__()
|
21 |
+
self.opt_scale = 2.97
|
22 |
+
self.codesz = 1
|
23 |
+
self.idx_dtype = torch.int32
|
24 |
+
self.packsz = 8
|
25 |
+
self.pack_out = False
|
26 |
+
self.version = 0
|
27 |
+
|
28 |
+
self.register_buffer('grid', _HI4B1C_CACHED)
|
29 |
+
if not inference:
|
30 |
+
self.register_buffer('grid_norm', _HI4B1C_NORM_CACHED)
|
31 |
+
'''
|
32 |
+
self.cuda()
|
33 |
+
samples = torch.distributions.multivariate_normal.MultivariateNormal(torch.zeros(1), torch.eye(1)).rsample([200000]).cuda()
|
34 |
+
print(samples.shape)
|
35 |
+
def fn_s(s):
|
36 |
+
err = (self.quantize(samples*s, False)/s - samples).float().norm()**2
|
37 |
+
err = err.cpu() / torch.numel(samples)
|
38 |
+
return err.cpu()
|
39 |
+
import scipy
|
40 |
+
print(scipy.optimize.minimize_scalar(fn_s, bounds=(0.1, 100)))
|
41 |
+
exit()
|
42 |
+
'''
|
43 |
+
|
44 |
+
def round(self, X, grid, grid_norm):
|
45 |
+
assert X.shape[-1] == self.codesz
|
46 |
+
Xqidx = (2 * X @ grid.T - grid_norm).argmax(-1)
|
47 |
+
return grid[Xqidx], Xqidx
|
48 |
+
|
49 |
+
def quantize(self, X, return_idx=True):
|
50 |
+
vals, idx = self.round(X, self.grid, self.grid_norm)
|
51 |
+
if not return_idx:
|
52 |
+
return vals
|
53 |
+
return vals, idx.to(self.idx_dtype)
|
54 |
+
|
55 |
+
def maybe_pack_idxs(self, idxs):
|
56 |
+
return \
|
57 |
+
(idxs[:, 0::self.packsz] << 4*7) + \
|
58 |
+
(idxs[:, 2::self.packsz] << 4*6) + \
|
59 |
+
(idxs[:, 4::self.packsz] << 4*5) + \
|
60 |
+
(idxs[:, 6::self.packsz] << 4*4) + \
|
61 |
+
(idxs[:, 1::self.packsz] << 4*3) + \
|
62 |
+
(idxs[:, 3::self.packsz] << 4*2) + \
|
63 |
+
(idxs[:, 5::self.packsz] << 4*1) + \
|
64 |
+
idxs[:, 7::self.packsz]
|
65 |
+
|
66 |
+
def by_idxs(self, idxs, packed=False):
|
67 |
+
if packed:
|
68 |
+
idxs = idxs.repeat_interleave(self.packsz, dim=-1)
|
69 |
+
idxs[:, 0::self.packsz] = (idxs[:, 0::self.packsz] >> 28) & 15
|
70 |
+
idxs[:, 2::self.packsz] = (idxs[:, 2::self.packsz] >> 24) & 15
|
71 |
+
idxs[:, 4::self.packsz] = (idxs[:, 4::self.packsz] >> 20) & 15
|
72 |
+
idxs[:, 6::self.packsz] = (idxs[:, 6::self.packsz] >> 16) & 15
|
73 |
+
idxs[:, 1::self.packsz] = (idxs[:, 1::self.packsz] >> 12) & 15
|
74 |
+
idxs[:, 3::self.packsz] = (idxs[:, 3::self.packsz] >> 8) & 15
|
75 |
+
idxs[:, 5::self.packsz] = (idxs[:, 5::self.packsz] >> 4) & 15
|
76 |
+
idxs[:, 7::self.packsz] = idxs[:, 7::self.packsz] & 15
|
77 |
+
|
78 |
+
return self.grid[idxs.int()]
|
79 |
+
|
80 |
+
|
81 |
+
class QuantizedHI4B1CLinear(nn.Module):
|
82 |
+
|
83 |
+
def __init__(self, device):
|
84 |
+
super().__init__()
|
85 |
+
self.codebook = HI4B1C_codebook(inference=True).to(torch.float16).to(device)
|
86 |
+
|
87 |
+
def forward(self,
|
88 |
+
input,
|
89 |
+
Qidxs,
|
90 |
+
SU,
|
91 |
+
SV,
|
92 |
+
Wscale,
|
93 |
+
had_left,
|
94 |
+
had_right,
|
95 |
+
K_left,
|
96 |
+
K_right,
|
97 |
+
rank=-1,
|
98 |
+
A=None,
|
99 |
+
B=None,
|
100 |
+
rescale_WH=False,
|
101 |
+
scaleWH=None,
|
102 |
+
packed=False):
|
103 |
+
n, m = len(SU), len(SV)
|
104 |
+
|
105 |
+
x = input.view(-1, n).to(torch.float32)
|
106 |
+
if rescale_WH:
|
107 |
+
x /= scaleWH
|
108 |
+
x = x * SU
|
109 |
+
x = matmul_hadUt_cuda(x, had_left, K_left)
|
110 |
+
|
111 |
+
if rank > 0:
|
112 |
+
Bx = x @ B.t().to(torch.float32)
|
113 |
+
ABx = Bx @ A.t().to(torch.float32)
|
114 |
+
|
115 |
+
num_scale = 1024
|
116 |
+
x = x / num_scale
|
117 |
+
x = x.to(torch.float16)
|
118 |
+
|
119 |
+
if packed:
|
120 |
+
W_decompressed = torch.zeros(m, n, dtype=torch.float16, device=x.device)
|
121 |
+
quiptools_cuda.decompress_hi4b1c_packed(Qidxs, self.codebook.grid, W_decompressed)
|
122 |
+
else:
|
123 |
+
W_decompressed = self.codebook.by_idxs(Qidxs, packed=False).reshape(-1, n)
|
124 |
+
|
125 |
+
z = x @ W_decompressed.t()
|
126 |
+
|
127 |
+
x = z.to(torch.float32)
|
128 |
+
x = x * (Wscale * num_scale)
|
129 |
+
|
130 |
+
if rank > 0:
|
131 |
+
x = x + ABx.to(torch.float32)
|
132 |
+
|
133 |
+
x = matmul_hadU_cuda(x, had_right, K_right)
|
134 |
+
x = x * SV
|
135 |
+
|
136 |
+
output = x.view(*input.shape[:-1], m)
|
137 |
+
|
138 |
+
return output
|
quip-sharp/lib/codebook/latticed4.py
ADDED
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
builds a deep-hole-centered D4 codebook
|
3 |
+
this is a codebook consisting of points on the lattice in R4
|
4 |
+
where each component is a half-integer
|
5 |
+
and the components sum to an even number
|
6 |
+
from this lattice, we select the points that have a norm-squared of at most 9
|
7 |
+
this results in a codebook of 256 points distributed as follows
|
8 |
+
8 with sorted abs of [1/2, 1/2, 1/2, 1/2]
|
9 |
+
8 [3/2, 3/2, 3/2, 3/2]
|
10 |
+
4c2 * 8 = 48 [1/2, 1/2. 3/2, 3/2]
|
11 |
+
4 * 8 = 32 [1/2, 1/2, 1/2, 3/2]
|
12 |
+
4 * 8 = 32 [1/2, 3/2, 3/2, 3/2]
|
13 |
+
4 * 8 = 32 [1/2, 1/2, 1/2, 5/2]
|
14 |
+
4 * 3 * 8 = 96 [1/2, 1/2, 3/2, 5/2]
|
15 |
+
"""
|
16 |
+
|
17 |
+
import torch
|
18 |
+
from torch import nn
|
19 |
+
import quiptools_cuda
|
20 |
+
|
21 |
+
from lib.utils.matmul_had import matmul_hadU_cuda, matmul_hadUt_cuda
|
22 |
+
|
23 |
+
_D4_CODESZ = 4
|
24 |
+
|
25 |
+
|
26 |
+
def code3_signs(i3, x):
|
27 |
+
if (i3 & (1 << 5)):
|
28 |
+
x[2] *= -1
|
29 |
+
if (i3 & (1 << 6)):
|
30 |
+
x[1] *= -1
|
31 |
+
if (sum(x) % 2 != 0):
|
32 |
+
x[3] *= -1
|
33 |
+
if (i3 & (1 << 7)):
|
34 |
+
for j in range(_D4_CODESZ):
|
35 |
+
x[j] *= -1
|
36 |
+
assert (sum(x) % 2 == 0)
|
37 |
+
return x
|
38 |
+
|
39 |
+
|
40 |
+
def code8_to_d4(i8):
|
41 |
+
assert ((i8 >= 0) and (i8 < 256))
|
42 |
+
i3 = i8 & (7 << 5)
|
43 |
+
i8 = i8 & 31
|
44 |
+
if i8 < 16:
|
45 |
+
if i8 < 8:
|
46 |
+
if i8 < 2:
|
47 |
+
if i8 < 1:
|
48 |
+
return code3_signs(i3, [0.5] * _D4_CODESZ)
|
49 |
+
else:
|
50 |
+
return code3_signs(i3, [1.5] * _D4_CODESZ)
|
51 |
+
else:
|
52 |
+
ibx = i8 >> 1
|
53 |
+
if i8 & 1:
|
54 |
+
x = [0.5] * _D4_CODESZ
|
55 |
+
x[0] = 1.5
|
56 |
+
x[ibx] = 1.5
|
57 |
+
else:
|
58 |
+
x = [1.5] * _D4_CODESZ
|
59 |
+
x[0] = 0.5
|
60 |
+
x[ibx] = 0.5
|
61 |
+
return code3_signs(i3, x)
|
62 |
+
else:
|
63 |
+
ibx = (i8 & 3)
|
64 |
+
if i8 < 8 + 4:
|
65 |
+
x = [0.5] * _D4_CODESZ
|
66 |
+
x[ibx] = 1.5
|
67 |
+
else:
|
68 |
+
x = [1.5] * _D4_CODESZ
|
69 |
+
x[ibx] = 0.5
|
70 |
+
return code3_signs(i3, x)
|
71 |
+
else:
|
72 |
+
if i8 < 16 + 4:
|
73 |
+
ibx = (i8 & 3)
|
74 |
+
x = [0.5] * _D4_CODESZ
|
75 |
+
x[ibx] = 2.5
|
76 |
+
return code3_signs(i3, x)
|
77 |
+
else:
|
78 |
+
ibx = i8 - 20
|
79 |
+
ib4 = ibx & 3
|
80 |
+
ib3 = ibx >> 2
|
81 |
+
x = [0.5] * _D4_CODESZ
|
82 |
+
x[ib4] = 1.5
|
83 |
+
if (ib3 >= ib4):
|
84 |
+
ib3 += 1
|
85 |
+
x[ib3] = 2.5
|
86 |
+
return code3_signs(i3, x)
|
87 |
+
|
88 |
+
|
89 |
+
def build_D4_CB():
|
90 |
+
CB = torch.zeros(256, _D4_CODESZ)
|
91 |
+
for i in range(256):
|
92 |
+
x = code8_to_d4(i)
|
93 |
+
for j in range(_D4_CODESZ):
|
94 |
+
CB[i, j] = x[j]
|
95 |
+
return CB
|
96 |
+
|
97 |
+
|
98 |
+
'''
|
99 |
+
def quantize(X, CB):
|
100 |
+
scale = X.square().mean().sqrt() / 1.21
|
101 |
+
X = X / scale
|
102 |
+
Xqidx = (2 * X @ CB.t() - (CB @ CB.t()).diag()).argmax(1)
|
103 |
+
return (CB[Xqidx, :] * scale, scale, Xqidx.to(torch.uint8))
|
104 |
+
def quantize_noscale_a(X, CB, A):
|
105 |
+
Xqidx = (2 * X @ A @ CB.t() - (CB @ A @ CB.t()).diag()).argmax(1)
|
106 |
+
return (CB[Xqidx, :], Xqidx.to(torch.uint8))
|
107 |
+
def quantize_full_lattice(X):
|
108 |
+
Xround = (X + 0.5).round() - 0.5
|
109 |
+
adjustParity = Xround.sum(1) % 2
|
110 |
+
furthestEntry = (X - Xround).abs().argmax(1)
|
111 |
+
furthestEntrySign = (X - Xround)[torch.arange(n), furthestEntry].sign()
|
112 |
+
Xround[torch.arange(n), furthestEntry] += furthestEntrySign * adjustParity
|
113 |
+
return Xround
|
114 |
+
'''
|
115 |
+
|
116 |
+
|
117 |
+
class D4_codebook(nn.Module):
|
118 |
+
|
119 |
+
def __init__(self, inference=False):
|
120 |
+
super(D4_codebook, self).__init__()
|
121 |
+
self.register_buffer("grid", build_D4_CB())
|
122 |
+
if not inference:
|
123 |
+
self.register_buffer('grid_norm', (self.grid @ self.grid.T).diag())
|
124 |
+
self.codesz = _D4_CODESZ
|
125 |
+
self.opt_scale = 1.21
|
126 |
+
self.idx_dtype = torch.uint8
|
127 |
+
self.packsz = 1
|
128 |
+
self.pack_out = False
|
129 |
+
self.version = 0
|
130 |
+
|
131 |
+
def _quantize_noscale(self, X, return_idx=True):
|
132 |
+
Xqidx = (2 * X @ self.grid.T - self.grid_norm).argmax(1)
|
133 |
+
if return_idx:
|
134 |
+
return self.grid[Xqidx, :], Xqidx.to(self.idx_dtype)
|
135 |
+
return self.grid[Xqidx, :]
|
136 |
+
|
137 |
+
def quantize(self, X, return_idx=True):
|
138 |
+
assert X.shape[-1] == self.codesz
|
139 |
+
return self._quantize_noscale(X, return_idx=return_idx)
|
140 |
+
|
141 |
+
def maybe_pack_idxs(self, idxs):
|
142 |
+
return idxs
|
143 |
+
|
144 |
+
def by_idxs(self, idxs, **kwargs):
|
145 |
+
return self.grid[idxs.int()]
|
146 |
+
|
147 |
+
|
148 |
+
class QuantizedD4Linear(nn.Module):
|
149 |
+
|
150 |
+
def __init__(self, device):
|
151 |
+
super().__init__()
|
152 |
+
self.codebook = D4_codebook(inference=True).to(torch.float16).to(device)
|
153 |
+
|
154 |
+
def forward(self,
|
155 |
+
input,
|
156 |
+
Qidxs,
|
157 |
+
SU,
|
158 |
+
SV,
|
159 |
+
Wscale,
|
160 |
+
had_left,
|
161 |
+
had_right,
|
162 |
+
K_left,
|
163 |
+
K_right,
|
164 |
+
rank=-1,
|
165 |
+
A=None,
|
166 |
+
B=None,
|
167 |
+
rescale_WH=False,
|
168 |
+
scaleWH=None,
|
169 |
+
**kwargs):
|
170 |
+
(m, n) = Qidxs.shape
|
171 |
+
|
172 |
+
x = input.view(-1, _D4_CODESZ * n).to(torch.float32)
|
173 |
+
if rescale_WH:
|
174 |
+
x /= scaleWH
|
175 |
+
x = matmul_hadUt_cuda(x * SU, had_left, K_left)
|
176 |
+
|
177 |
+
if rank > 0:
|
178 |
+
Bx = x @ B.t().to(torch.float32)
|
179 |
+
ABx = Bx @ A.t().to(torch.float32)
|
180 |
+
|
181 |
+
x = (x / 1024).to(torch.float16)
|
182 |
+
|
183 |
+
if (x.shape[0] <= 8):
|
184 |
+
if (x.shape[0] == 8):
|
185 |
+
x_padded = x.contiguous()
|
186 |
+
else:
|
187 |
+
x_padded = torch.zeros(8, n * _D4_CODESZ, dtype=torch.float16, device=x.device)
|
188 |
+
x_padded[0:(x.shape[0]), :] = x
|
189 |
+
z = torch.zeros(8, m, dtype=x.dtype, device=x.device)
|
190 |
+
quiptools_cuda.lookupmatmul_d4_k8(x_padded, Qidxs, self.codebook.grid, z)
|
191 |
+
z = z[0:(x.shape[0]), :]
|
192 |
+
elif (x.shape[0] <= 16):
|
193 |
+
if (x.shape[0] == 16):
|
194 |
+
x_padded = x.contiguous()
|
195 |
+
else:
|
196 |
+
x_padded = torch.zeros(16, n * _D4_CODESZ, dtype=torch.float16, device=x.device)
|
197 |
+
x_padded[0:(x.shape[0]), :] = x
|
198 |
+
z = torch.zeros(16, m, dtype=x.dtype, device=x.device)
|
199 |
+
quiptools_cuda.lookupmatmul_d4_k16(x_padded, Qidxs, self.codebook.grid, z)
|
200 |
+
z = z[0:(x.shape[0]), :]
|
201 |
+
elif (x.shape[0] <= 32):
|
202 |
+
if (x.shape[0] == 32):
|
203 |
+
x_padded = x.contiguous()
|
204 |
+
else:
|
205 |
+
x_padded = torch.zeros(32, n * _D4_CODESZ, dtype=torch.float16, device=x.device)
|
206 |
+
x_padded[0:(x.shape[0]), :] = x
|
207 |
+
z = torch.zeros(32, m, dtype=x.dtype, device=x.device)
|
208 |
+
quiptools_cuda.lookupmatmul_d4_k32(x_padded, Qidxs, self.codebook.grid, z)
|
209 |
+
z = z[0:(x.shape[0]), :]
|
210 |
+
else:
|
211 |
+
# manifest the matrix
|
212 |
+
W_decompressed = torch.zeros(m, n * _D4_CODESZ, dtype=torch.float16, device=x.device)
|
213 |
+
quiptools_cuda.decompress_d4(Qidxs, self.codebook.grid, W_decompressed)
|
214 |
+
z = x @ W_decompressed.t()
|
215 |
+
|
216 |
+
x = z.to(torch.float32) * (Wscale * 1024)
|
217 |
+
if rank > 0:
|
218 |
+
x = x + ABx.to(torch.float32)
|
219 |
+
|
220 |
+
return (matmul_hadU_cuda(x, had_right, K_right) * SV).view(*input.shape[:-1], m)
|
quip-sharp/lib/codebook/latticee8_padded12.py
ADDED
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
D8^ = D8 + 1/2 intersected with ball of radius sqrt(10)
|
3 |
+
|D8^| has 227 entries
|
4 |
+
We then add 29 entries from the set of vectors with 5 3/2 and 3 1/2
|
5 |
+
The total codebook is all 2^7 flips of these 256 entries (2^15) +- 1/4
|
6 |
+
which makes 2^16 entries.
|
7 |
+
This corresponds to a subset of E8 + 1/4
|
8 |
+
"""
|
9 |
+
|
10 |
+
import torch
|
11 |
+
import math
|
12 |
+
from torch import nn
|
13 |
+
from functools import cache
|
14 |
+
import itertools
|
15 |
+
from lib.utils.matmul_had import matmul_hadU_cuda, matmul_hadUt_cuda
|
16 |
+
import quiptools_cuda
|
17 |
+
|
18 |
+
_E8P_CODESZ = 8
|
19 |
+
_INT_MAP = 2**(torch.arange(_E8P_CODESZ).flip(0))
|
20 |
+
|
21 |
+
|
22 |
+
def int2mask(i, int_map):
|
23 |
+
return ((i & int_map) > 0).int()
|
24 |
+
|
25 |
+
|
26 |
+
def mask2int(mask, int_map):
|
27 |
+
return (int_map.unsqueeze(0) * mask.int()).sum(dim=-1)
|
28 |
+
|
29 |
+
|
30 |
+
def get_abs_grid():
|
31 |
+
intr = torch.arange(-4, 4)
|
32 |
+
d8 = torch.cartesian_prod(*[intr] * _E8P_CODESZ).float() + 1 / 2
|
33 |
+
d8m2 = (d8.sum(dim=-1) % 2 == 0)
|
34 |
+
d8n = d8.norm(dim=-1)**2 <= 10
|
35 |
+
d8abs = torch.unique(d8[sorted(torch.where(d8m2 * d8n)[0])].abs(), dim=0)
|
36 |
+
|
37 |
+
norm12 = torch.tensor([
|
38 |
+
[3, 1, 1, 1, 3, 3, 3, 3],
|
39 |
+
[1, 3, 1, 1, 3, 3, 3, 3],
|
40 |
+
[1, 1, 3, 1, 3, 3, 3, 3],
|
41 |
+
[1, 1, 1, 3, 3, 3, 3, 3],
|
42 |
+
[3, 3, 3, 1, 3, 3, 1, 1],
|
43 |
+
[3, 3, 3, 1, 3, 1, 3, 1],
|
44 |
+
[3, 3, 3, 1, 1, 3, 3, 1],
|
45 |
+
[3, 3, 3, 1, 3, 1, 1, 3],
|
46 |
+
[3, 3, 3, 1, 1, 3, 1, 3],
|
47 |
+
[3, 3, 3, 1, 1, 1, 3, 3],
|
48 |
+
[3, 3, 1, 3, 3, 3, 1, 1],
|
49 |
+
[3, 3, 1, 3, 3, 1, 3, 1],
|
50 |
+
[3, 3, 1, 3, 1, 3, 3, 1],
|
51 |
+
[3, 3, 1, 3, 3, 1, 1, 3],
|
52 |
+
[3, 3, 1, 3, 1, 3, 1, 3],
|
53 |
+
[3, 3, 1, 3, 1, 1, 3, 3],
|
54 |
+
[3, 1, 3, 3, 3, 3, 1, 1],
|
55 |
+
[3, 1, 3, 3, 3, 1, 3, 1],
|
56 |
+
[3, 1, 3, 3, 1, 3, 3, 1],
|
57 |
+
[3, 1, 3, 3, 3, 1, 1, 3],
|
58 |
+
[3, 1, 3, 3, 1, 3, 1, 3],
|
59 |
+
[1, 3, 3, 3, 1, 1, 3, 3],
|
60 |
+
[1, 3, 3, 3, 3, 3, 1, 1],
|
61 |
+
[1, 3, 3, 3, 3, 1, 3, 1],
|
62 |
+
[1, 3, 3, 3, 1, 3, 3, 1],
|
63 |
+
[1, 3, 3, 3, 3, 1, 1, 3],
|
64 |
+
[1, 3, 3, 3, 1, 3, 1, 3],
|
65 |
+
[1, 3, 3, 3, 1, 1, 3, 3],
|
66 |
+
[3, 3, 1, 1, 3, 3, 3, 1],
|
67 |
+
]) / 2
|
68 |
+
return torch.concat([d8abs, norm12], dim=0)
|
69 |
+
|
70 |
+
|
71 |
+
def get_full_grid(abs_grid):
|
72 |
+
"""
|
73 |
+
idx format:
|
74 |
+
- first 8 bits = which of the 256 entries in the abs grid
|
75 |
+
- next 7 bits = which of the right 7 dims to negate (8th can be inferred)
|
76 |
+
- last bit = +1/4 if true else -1/4
|
77 |
+
"""
|
78 |
+
is_even_flips = abs_grid.sum(dim=-1) % 2 == 0
|
79 |
+
abs_idxs = torch.arange(len(abs_grid)) << _E8P_CODESZ
|
80 |
+
entries = [[], []]
|
81 |
+
idxs = [[], []]
|
82 |
+
for i in range(2**(_E8P_CODESZ - 1)):
|
83 |
+
mask = int2mask(i, _INT_MAP)
|
84 |
+
mask_even = (mask.sum(dim=-1) % 2 == 0)
|
85 |
+
mask = mask.unsqueeze(0).repeat(len(abs_grid), 1)
|
86 |
+
mask[:, 0] = mask_even != is_even_flips
|
87 |
+
mask = 1 - 2 * mask
|
88 |
+
entries[0].append(abs_grid * mask + 1 / 4)
|
89 |
+
idxs[0].append(abs_idxs + (i << 1) + 1)
|
90 |
+
entries[1].append(abs_grid * mask - 1 / 4)
|
91 |
+
idxs[1].append(abs_idxs + (i << 1))
|
92 |
+
|
93 |
+
for i in range(2):
|
94 |
+
entries[i] = torch.concat(entries[i], dim=0)
|
95 |
+
idxs[i] = torch.concat(idxs[i], dim=0)
|
96 |
+
entries = torch.concat(entries, dim=0)
|
97 |
+
idxs = torch.concat(idxs, dim=0)
|
98 |
+
return entries, idxs
|
99 |
+
|
100 |
+
|
101 |
+
_E8P_ABS_CACHED = get_abs_grid()
|
102 |
+
_E8P_GRID, _E8P_GRID_IDX = get_full_grid(_E8P_ABS_CACHED)
|
103 |
+
|
104 |
+
|
105 |
+
class E8P12_codebook(nn.Module):
|
106 |
+
|
107 |
+
def __init__(self, inference=False):
|
108 |
+
super(E8P12_codebook, self).__init__()
|
109 |
+
self.opt_scale = 1 #.03#/1.09
|
110 |
+
self.codesz = _E8P_CODESZ
|
111 |
+
self.idx_dtype = torch.int16
|
112 |
+
self.idx_offset = -2**15
|
113 |
+
self.packsz = 1
|
114 |
+
self.pack_out = False
|
115 |
+
self.version = 0
|
116 |
+
|
117 |
+
self.register_buffer('grid_abs', _E8P_ABS_CACHED)
|
118 |
+
self.register_buffer('grid_abs_even', self.grid_abs.sum(dim=-1) % 2 == 0)
|
119 |
+
|
120 |
+
if not inference:
|
121 |
+
self.register_buffer('int_map', _INT_MAP)
|
122 |
+
self.register_buffer('grid', _E8P_GRID)
|
123 |
+
self.register_buffer('grid_idx_map',
|
124 |
+
(_E8P_GRID_IDX + self.idx_offset).to(self.idx_dtype))
|
125 |
+
idx_lut = torch.zeros(_E8P_GRID_IDX.shape).int()
|
126 |
+
idx_lut[_E8P_GRID_IDX] = torch.arange(len(_E8P_GRID_IDX)).int()
|
127 |
+
self.register_buffer('grid_idx_inv', idx_lut)
|
128 |
+
|
129 |
+
self.register_buffer('grid_norm', torch.diag(self.grid @ self.grid.T))
|
130 |
+
grid_part = self.grid[:len(self.grid) // 2] - 1 / 4
|
131 |
+
idxs = torch.where(
|
132 |
+
((grid_part[:, 1:] < 0).sum(dim=-1) <= 1) * \
|
133 |
+
(grid_part[:, 1:].min(dim=-1).values >= -0.5)
|
134 |
+
)[0]
|
135 |
+
grid_part = grid_part[idxs]
|
136 |
+
self.register_buffer('grid_part', grid_part)
|
137 |
+
self.register_buffer('grid_part_norm', torch.diag(grid_part @ grid_part.T))
|
138 |
+
allcombo_idx, idx_map = self.iterate_mask()
|
139 |
+
self.register_buffer('allcombo_idx', allcombo_idx)
|
140 |
+
self.register_buffer('idx_map', idx_map)
|
141 |
+
'''
|
142 |
+
self.to('cuda')
|
143 |
+
samples = torch.distributions.multivariate_normal.MultivariateNormal(torch.zeros(8), torch.eye(8)).rsample([2000000]).cuda()
|
144 |
+
for s in torch.arange(0.8, 1.2, 0.01):
|
145 |
+
print(s, ((self.quantize(samples*s, False)/s - samples).norm(dim=-1)**2).mean())
|
146 |
+
exit()
|
147 |
+
'''
|
148 |
+
|
149 |
+
def iterate_mask(self, device=0):
|
150 |
+
flips = torch.stack([((torch.tensor([i]) & self.int_map) > 0).int()
|
151 |
+
for i in range(2**_E8P_CODESZ)]).to(device)
|
152 |
+
raw_idx = torch.where(flips.sum(dim=-1) % 2 == 0)[0]
|
153 |
+
flips = 1 - 2 * flips[raw_idx]
|
154 |
+
idx_map = torch.zeros(2**_E8P_CODESZ, dtype=torch.int32)
|
155 |
+
for i in range(len(raw_idx)):
|
156 |
+
idx_map[raw_idx[i]] = i
|
157 |
+
allcombo = flips.unsqueeze(1) * self.grid_part.unsqueeze(0).to(device)
|
158 |
+
allcombo_idx = torch.zeros(allcombo.shape[0:2]).int()
|
159 |
+
for i in range(len(allcombo)):
|
160 |
+
allcombo_idx[i] = self.round(allcombo[i], self.grid.to(device),
|
161 |
+
self.grid_norm.to(device))[1]
|
162 |
+
return allcombo_idx.cpu(), idx_map.cpu()
|
163 |
+
|
164 |
+
def round(self, X, grid, grid_norm):
|
165 |
+
assert X.shape[-1] == self.codesz
|
166 |
+
Xqidx = (2 * X @ grid.T - grid_norm).argmax(-1)
|
167 |
+
return grid[Xqidx], Xqidx
|
168 |
+
|
169 |
+
def fast_quantize_part(self, X):
|
170 |
+
X_part = torch.abs(X)
|
171 |
+
X_odd = torch.where((X < 0).sum(dim=-1) % 2 != 0)[0]
|
172 |
+
X_part[X_odd, 0] = -X_part[X_odd, 0]
|
173 |
+
mask = 1 - 2 * (X < 0).to(torch.float32)
|
174 |
+
mask[X_odd, 0] = -mask[X_odd, 0]
|
175 |
+
roundout, Xqidx = self.round(X_part, self.grid_part, self.grid_part_norm)
|
176 |
+
vals = roundout * mask
|
177 |
+
real_idx = self.allcombo_idx[self.idx_map[mask2int((1 - mask) / 2, self.int_map)], Xqidx]
|
178 |
+
err = (X - vals).norm(dim=-1)
|
179 |
+
return vals, real_idx, err
|
180 |
+
|
181 |
+
def quantize(self, X, return_idx=True):
|
182 |
+
X_plus = X + 1 / 4 # quantize X to D8^ - 1/4
|
183 |
+
X_minus = X - 1 / 4 # quantize X to D8^ + 1/4
|
184 |
+
|
185 |
+
plus_vals, plus_idx, plus_err = self.fast_quantize_part(X_plus)
|
186 |
+
minus_vals, minus_idx, minus_err = self.fast_quantize_part(X_minus)
|
187 |
+
plus_idx = plus_idx + 2**15
|
188 |
+
|
189 |
+
which = plus_err < minus_err
|
190 |
+
final_vals = torch.where(which.unsqueeze(-1), plus_vals - 1 / 4, minus_vals + 1 / 4)
|
191 |
+
|
192 |
+
if return_idx:
|
193 |
+
final_idxs = self.grid_idx_map[torch.where(which, plus_idx, minus_idx)]
|
194 |
+
return final_vals, final_idxs
|
195 |
+
|
196 |
+
return final_vals
|
197 |
+
|
198 |
+
def maybe_pack_idxs(self, idxs):
|
199 |
+
return idxs
|
200 |
+
|
201 |
+
def by_idxs(self, idxs, **kwargs):
|
202 |
+
return self.grid[self.grid_idx_inv[idxs.int() - self.idx_offset]]
|
203 |
+
|
204 |
+
|
205 |
+
class QuantizedE8P12Linear(nn.Module):
|
206 |
+
|
207 |
+
def __init__(self, device):
|
208 |
+
super().__init__()
|
209 |
+
self.codebook = E8P12_codebook(inference=True).to(torch.float16).to(device)
|
210 |
+
self.codebook_matvec = torch.zeros((256, ), dtype=torch.int64, device=device)
|
211 |
+
for i in range(8):
|
212 |
+
chunk = (self.codebook.grid_abs[:, i] * 4).to(torch.int64)
|
213 |
+
self.codebook_matvec |= chunk << (i * 8)
|
214 |
+
|
215 |
+
def forward(self,
|
216 |
+
input,
|
217 |
+
Qidxs,
|
218 |
+
SU,
|
219 |
+
SV,
|
220 |
+
Wscale,
|
221 |
+
had_left,
|
222 |
+
had_right,
|
223 |
+
K_left,
|
224 |
+
K_right,
|
225 |
+
rank=-1,
|
226 |
+
A=None,
|
227 |
+
B=None,
|
228 |
+
rescale_WH=False,
|
229 |
+
scaleWH=None,
|
230 |
+
**kwargs):
|
231 |
+
(m, n) = Qidxs.shape
|
232 |
+
|
233 |
+
x = input.view(-1, n * _E8P_CODESZ).to(torch.float32)
|
234 |
+
if rescale_WH:
|
235 |
+
x /= scaleWH
|
236 |
+
x = x * SU
|
237 |
+
x = matmul_hadUt_cuda(x, had_left, K_left)
|
238 |
+
|
239 |
+
if rank > 0:
|
240 |
+
Bx = x @ B.t().to(torch.float32)
|
241 |
+
ABx = Bx @ A.t().to(torch.float32)
|
242 |
+
|
243 |
+
# TODO: find the optimal threshold
|
244 |
+
if x.size(0) < 6:
|
245 |
+
x = quiptools_cuda.decode_matmul_e8p(x, Qidxs - 0x8000,
|
246 |
+
self.codebook_matvec).to(torch.float32)
|
247 |
+
else:
|
248 |
+
W_decompressed = torch.zeros(m,
|
249 |
+
n * _E8P_CODESZ,
|
250 |
+
device=Qidxs.device,
|
251 |
+
dtype=torch.float16)
|
252 |
+
quiptools_cuda.decompress_e8p_origorder(Qidxs, self.codebook.grid_abs,
|
253 |
+
self.codebook.grid_abs_even, W_decompressed)
|
254 |
+
x = (x.to(torch.float16) @ W_decompressed.T).to(torch.float32)
|
255 |
+
|
256 |
+
x *= Wscale
|
257 |
+
|
258 |
+
if rank > 0:
|
259 |
+
x = x + ABx.to(torch.float32)
|
260 |
+
|
261 |
+
x = matmul_hadU_cuda(x, had_right, K_right)
|
262 |
+
x = x * SV
|
263 |
+
|
264 |
+
output = x.view(*input.shape[:-1], m)
|
265 |
+
return output
|
quip-sharp/lib/linear/__init__.py
ADDED
File without changes
|
quip-sharp/lib/linear/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (180 Bytes). View file
|
|
quip-sharp/lib/linear/__pycache__/__init__.cpython-39.pyc
ADDED
Binary file (135 Bytes). View file
|
|
quip-sharp/lib/linear/__pycache__/quantized_linear.cpython-310.pyc
ADDED
Binary file (2.37 kB). View file
|
|