File size: 11,620 Bytes
e53bffd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
from qmllm.quantization.qlinear import WALinear
import torch
import torch.nn as nn
from tqdm import tqdm
from transformers.models.bloom.modeling_bloom import BloomForCausalLM
from transformers.models.opt.modeling_opt import OPTForCausalLM
from transformers.models.llama.modeling_llama import LlamaForCausalLM

def quantize_opt(
    model, weight_quant="per_tensor", act_quant="per_tensor", w_bit=4, a_bit=8, quantize_bmm_input=True
):
    from transformers.models.opt.modeling_opt import (
        OPTAttention,
        OPTDecoderLayer,
    )

    for name, m in model.model.named_modules():
        if isinstance(m, OPTDecoderLayer):
            m.fc1 = WALinear.from_float(
                m.fc1, weight_quant=weight_quant, act_quant=act_quant, w_bit=w_bit, a_bit=a_bit,
            )
            m.fc2 = WALinear.from_float(
                m.fc2, weight_quant=weight_quant, act_quant=act_quant, w_bit=w_bit, a_bit=a_bit,
            )
        elif isinstance(m, OPTAttention):
            # Her we simulate quantizing BMM inputs by quantizing the output of q_proj, k_proj, v_proj
            m.q_proj = WALinear.from_float(
                m.q_proj,
                weight_quant=weight_quant,
                act_quant=act_quant,
                w_bit=w_bit, a_bit=a_bit,
                quantize_output=quantize_bmm_input,
            )
            m.k_proj = WALinear.from_float(
                m.k_proj,
                weight_quant=weight_quant,
                act_quant=act_quant,
                w_bit=w_bit, a_bit=a_bit,
                quantize_output=quantize_bmm_input,
            )
            m.v_proj = WALinear.from_float(
                m.v_proj,
                weight_quant=weight_quant,
                act_quant=act_quant,
                w_bit=w_bit, a_bit=a_bit,
                quantize_output=quantize_bmm_input,
            )
            m.out_proj = WALinear.from_float(
                m.out_proj, weight_quant=weight_quant, act_quant=act_quant, w_bit=w_bit, a_bit=a_bit,
            )
    return model


def quantize_llama_like(
    model, weight_quant="per_channel", act_quant="per_token", w_bit=4, a_bit=8, quantize_bmm_input=False
):
    from transformers.models.llama.modeling_llama import (
        LlamaAttention,
        LlamaMLP,
    )

    from transformers.models.mistral.modeling_mistral import (
        MistralAttention,
        MistralMLP,
    )

    for name, m in model.model.named_modules():
        if isinstance(m, (LlamaMLP, MistralMLP)):
            m.gate_proj = WALinear.from_float(
                m.gate_proj, weight_quant=weight_quant, act_quant=act_quant, w_bit=w_bit, a_bit=a_bit,
            )
            m.up_proj = WALinear.from_float(
                m.up_proj, weight_quant=weight_quant, act_quant=act_quant, w_bit=w_bit, a_bit=a_bit,
            )
            m.down_proj = WALinear.from_float(
                m.down_proj, weight_quant=weight_quant, act_quant=act_quant, w_bit=w_bit, a_bit=a_bit,
            )
        elif isinstance(m, (LlamaAttention, MistralAttention)):
            # Her we simulate quantizing BMM inputs by quantizing the output of q_proj, k_proj, v_proj
            m.q_proj = WALinear.from_float(
                m.q_proj,
                weight_quant=weight_quant,
                act_quant=act_quant,
                quantize_output=quantize_bmm_input,
                w_bit=w_bit, a_bit=a_bit,
            )
            m.k_proj = WALinear.from_float(
                m.k_proj,
                weight_quant=weight_quant,
                act_quant=act_quant,
                quantize_output=quantize_bmm_input,
                w_bit=w_bit, a_bit=a_bit,
            )
            m.v_proj = WALinear.from_float(
                m.v_proj,
                weight_quant=weight_quant,
                act_quant=act_quant,
                w_bit=w_bit, a_bit=a_bit,
                quantize_output=quantize_bmm_input,
            )
            m.o_proj = WALinear.from_float(
                m.o_proj, weight_quant=weight_quant, act_quant=act_quant, w_bit=w_bit, a_bit=a_bit,
            )
    return model


def quantize_mixtral(
    model, weight_quant="per_channel", act_quant="per_token", w_bit=4, a_bit=8, quantize_bmm_input=False
):
    from transformers.models.mixtral.modeling_mixtral import (
        MixtralAttention,
        MixtralSparseMoeBlock,
        MixtralBLockSparseTop2MLP,
    )

    for name, m in model.model.named_modules():
        if isinstance(m, MixtralBLockSparseTop2MLP):
            m.w1 = WALinear.from_float(
                m.w1, weight_quant=weight_quant, act_quant=act_quant, w_bit=w_bit, a_bit=a_bit,
            )
            m.w2 = WALinear.from_float(
                m.w2, weight_quant=weight_quant, act_quant=act_quant, w_bit=w_bit, a_bit=a_bit,
            )
            m.w3 = WALinear.from_float(
                m.w3, weight_quant=weight_quant, act_quant=act_quant, w_bit=w_bit, a_bit=a_bit,
            )
        elif isinstance(m, MixtralAttention):
            # Her we simulate quantizing BMM inputs by quantizing the output of q_proj, k_proj, v_proj
            m.q_proj = WALinear.from_float(
                m.q_proj,
                weight_quant=weight_quant,
                act_quant=act_quant,
                w_bit=w_bit, a_bit=a_bit,
                quantize_output=quantize_bmm_input,
            )
            m.k_proj = WALinear.from_float(
                m.k_proj,
                weight_quant=weight_quant,
                act_quant=act_quant,
                w_bit=w_bit, a_bit=a_bit,
                quantize_output=quantize_bmm_input,
            )
            m.v_proj = WALinear.from_float(
                m.v_proj,
                weight_quant=weight_quant,
                act_quant=act_quant,
                w_bit=w_bit, a_bit=a_bit,
                quantize_output=quantize_bmm_input,
            )
            m.o_proj = WALinear.from_float(
                m.o_proj, weight_quant=weight_quant, act_quant=act_quant, w_bit=w_bit, a_bit=a_bit,
            )
        elif isinstance(m, MixtralSparseMoeBlock):
            m.gate = WALinear.from_float(
                m.gate, weight_quant=weight_quant, act_quant=act_quant, w_bit=w_bit, a_bit=a_bit,
            )
    return model


def quantize_falcon(
    model, weight_quant="per_channel", act_quant="per_token", w_bit=4, a_bit=8, quantize_bmm_input=True
):
    from transformers.models.falcon.modeling_falcon import (
        FalconAttention,
        FalconMLP,
    )

    for name, m in model.named_modules():
        if isinstance(m, FalconMLP):
            m.dense_h_to_4h = WALinear.from_float(
                m.dense_h_to_4h, weight_quant=weight_quant, act_quant=act_quant, w_bit=w_bit, a_bit=a_bit,
            )
            m.dense_4h_to_h = WALinear.from_float(
                m.dense_4h_to_h, weight_quant=weight_quant, act_quant=act_quant, w_bit=w_bit, a_bit=a_bit,
            )
        elif isinstance(m, FalconAttention):
            # Her we simulate quantizing BMM inputs by quantizing the output of q_proj, k_proj, v_proj
            m.query_key_value = WALinear.from_float(
                m.query_key_value,
                weight_quant=weight_quant,
                act_quant=act_quant,
                w_bit=w_bit, a_bit=a_bit,
                quantize_output=quantize_bmm_input,
            )
            m.dense = WALinear.from_float(
                m.dense, weight_quant=weight_quant, act_quant=act_quant, w_bit=w_bit, a_bit=a_bit,
            )
    return model


def quantize_model(
    model, weight_quant="per_channel", act_quant="per_token", w_bit=4, a_bit=8, quantize_bmm_input=False
):
    from transformers.models.opt.modeling_opt import OPTPreTrainedModel
    from transformers.models.llama.modeling_llama import LlamaPreTrainedModel
    from transformers.models.mistral.modeling_mistral import MistralPreTrainedModel
    from transformers.models.mixtral.modeling_mixtral import MixtralPreTrainedModel
    from transformers.models.falcon.modeling_falcon import FalconPreTrainedModel

    if isinstance(model, OPTPreTrainedModel):
        return quantize_opt(
            model,
            weight_quant=weight_quant,
            act_quant=act_quant,
            w_bit=w_bit, a_bit=a_bit,
            quantize_bmm_input=quantize_bmm_input,
        )
    elif isinstance(model, (LlamaPreTrainedModel, MistralPreTrainedModel)):
        return quantize_llama_like(
            model,
            weight_quant=weight_quant,
            act_quant=act_quant,
            w_bit=w_bit, a_bit=a_bit,
            quantize_bmm_input=quantize_bmm_input,
        )
    elif isinstance(model, MixtralPreTrainedModel):
        return quantize_mixtral(
            model,
            weight_quant=weight_quant,
            act_quant=act_quant,
            w_bit=w_bit, a_bit=a_bit,
            quantize_bmm_input=quantize_bmm_input,
        )
    elif isinstance(model, FalconPreTrainedModel):
        return quantize_falcon(
            model,
            weight_quant=weight_quant,
            act_quant=act_quant,
            w_bit=w_bit, a_bit=a_bit,
            quantize_bmm_input=quantize_bmm_input,
        )
    else:
        raise ValueError(f"Unsupported model type: {type(model)}")


def get_named_linears(module):
    return {name: m for name, m in module.named_modules() if isinstance(m, nn.Linear)}


def get_blocks(model):
    if model.__class__.__name__ == "LlamaForCausalLM":
        layers = model.model.layers
    elif model.__class__.__name__ == "LlavaLlamaForCausalLM":
        # layers = [model.model.layers, model.model.vision_tower.vision_tower.vision_model.encoder.layers]
        layers = model.model.layers
    elif model.__class__.__name__ == "LlavaQwenForCausalLM":
        layers = model.model.layers
    elif model.__class__.__name__ == "InternLM2ForCausalLM":
        layers = model.model.layers
    elif model.__class__.__name__ == "InternVLChatModel":
        layers = model.language_model.model.layers
    elif model.__class__.__name__ == "Qwen2VLForConditionalGeneration":
        layers = model.model.layers
    elif model.__class__.__name__ == "LlavaLlamaModel":
        layers = model.llm.model.layers
    elif isinstance(model, OPTForCausalLM):
        layers = model.model.decoder.layers
    elif isinstance(model, BloomForCausalLM):
        layers = model.transformer.h
    elif "mpt" in str(model.__class__).lower():
        layers = model.transformer.blocks
    elif "falcon" in str(model.__class__).lower():
        layers = model.transformer.h
    elif "bigcode" in str(model.__class__).lower():
        layers = model.transformer.h
    elif "neox" in str(model.__class__).lower():
        layers = model.gpt_neox.layers
    else:
        raise NotImplementedError(type(model))
    return layers


def get_module_by_name_suffix(model, module_name: str):
    for name, module in model.named_modules():
        if name.endswith(module_name):
            return module
        

@torch.no_grad()
def pseudo_quantize_model_weight_act(
    model,
    w_bit,
    a_bit,
):
    
    layers = get_blocks(model)
    for i in tqdm(range(len(layers)), desc="pseudo weight activation quantization..."):
        named_linears = get_named_linears(layers[i])
        for n, m in named_linears.items():
            new_linear = WALinear.from_float(m, weight_quant="per_channel", act_quant="per_token", w_bit=w_bit, a_bit=a_bit)
            father_module = get_module_by_name_suffix(layers[i], '.'.join(n.split(".")[:-1]))
            setattr(father_module, n.split('.')[-1], new_linear)
            del new_linear, m
            torch.cuda.empty_cache()