File size: 7,791 Bytes
2051791
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import torch
import torch.nn as nn
import numpy as np
from transformers import AutoTokenizer, AutoModelForCausalLM
import tqdm
import json
import math
import torch.nn.functional as F


from datasets import load_dataset

@torch.no_grad()
def quantize_weight_per_channel_absmax(w, n_bits=8):
    # w: (out_features, in_features)
    scales = w.abs().max(dim=-1, keepdim=True)[0]
    q_max = 2 ** (n_bits - 1) - 1
    scales.clamp_(min=1e-5).div_(q_max)
    w.div_(scales).round_().mul_(scales)
    return w


@torch.no_grad()
def quantize_weight_per_tensor_absmax(w, n_bits=8):
    # w: (out_features, in_features)
    scales = w.abs().max()
    q_max = 2 ** (n_bits - 1) - 1
    scales.clamp_(min=1e-5).div_(q_max)
    w.div_(scales).round_().mul_(scales)
    return w

class W8A16Linear(nn.Module):
    def __init__(
        self,
        # bit_width,
        in_features,
        out_features,
        bias=True,
        quantize_output=False,
    ):
        super().__init__()
        # self.bit_width = bit_width
        self.in_features = in_features
        self.out_features = out_features

        self.register_buffer(
            "weight",
            torch.randn(
                self.out_features,
                self.in_features,
                dtype=torch.float16,
                requires_grad=False,
            ),
        )
        if bias:
            self.register_buffer(
                "bias",
                torch.zeros(
                    (1, self.out_features), dtype=torch.float16, requires_grad=False
                ),
            )
        else:
            self.register_buffer("bias", None)

    def to(self, *args, **kwargs):
        super(W8A16Linear, self).to(*args, **kwargs)
        self.weight = self.weight.to(*args, **kwargs)
        if self.bias is not None:
            self.bias = self.bias.to(*args, **kwargs)
        return self

    @torch.no_grad()
    def forward(self, x):
        y = torch.functional.F.linear(x, self.weight, self.bias)
        return y

    @staticmethod
    def from_float(
        bit, module, weight_quant="per_channel", quantize_output=False
    ):
        assert isinstance(module, torch.nn.Linear)
        new_module = W8A16Linear(
            # bit,
            module.in_features,
            module.out_features,
            module.bias is not None,
            quantize_output=quantize_output,
        )
        if weight_quant == "per_channel":
            new_module.weight = quantize_weight_per_channel_absmax(module.weight, bit)
        elif weight_quant == "per_tensor":
            new_module.weight = quantize_weight_per_tensor_absmax(module.weight, bit)
        else:
            raise ValueError(f"Invalid weight_quant: {weight_quant}")
        new_module.weight_quant_name = weight_quant
        
        if module.bias is not None:
            new_module.bias = module.bias
        return new_module

    def __repr__(self):
        return f"W8A16Linear({self.in_features}, {self.out_features}, bias={self.bias is not None}, weight_quant={self.weight_quant_name})"

def quantize_llama_like(
    model, mlp_quant, self_attn_quant, low_bit, bit_layers, weight_quant="per_channel", quantize_bmm_input=False
):
    from transformers.models.llama.modeling_llama import (
        LlamaAttention,
        LlamaMLP,
    )

    for name, m in model.model.named_modules():
        # print(name)
        if isinstance(m, LlamaMLP):
            if low_bit == 0:
                continue
            else:
                if name in mlp_quant:
                    # bit = low_bit
                    layer_id = int(name.split('.')[1])
                    bit = bit_layers[layer_id]
                    print(f'{name} {bit} bit quant ')
                else:
                    bit = low_bit
                    print(f'{name} {bit} bit quant ')


            m.gate_proj = W8A16Linear.from_float(
                bit, m.gate_proj, weight_quant=weight_quant
            )
            m.up_proj = W8A16Linear.from_float(
                bit, m.up_proj, weight_quant=weight_quant
            )
            m.down_proj = W8A16Linear.from_float(
                bit, m.down_proj, weight_quant=weight_quant
            )
        elif isinstance(m, LlamaAttention):
            if low_bit == 0:
                continue
            else:
                if name in self_attn_quant:
                    # bit = low_bit
                    layer_id = int(name.split('.')[1])
                    bit = bit_layers[layer_id]
                    print(f'{name} {bit} bit quant ')
                else:
                    bit = low_bit
                    print(f'{name} {bit} bit quant ')


            m.q_proj = W8A16Linear.from_float(
                bit,  
                m.q_proj,
                weight_quant=weight_quant,
                quantize_output=quantize_bmm_input,
            )
            m.k_proj = W8A16Linear.from_float(
                bit, 
                m.k_proj,
                weight_quant=weight_quant,
                quantize_output=quantize_bmm_input,
            )
            m.v_proj = W8A16Linear.from_float(
                bit, 
                m.v_proj,
                weight_quant=weight_quant,
                quantize_output=quantize_bmm_input,
            )
            m.o_proj = W8A16Linear.from_float(
                bit, m.o_proj, weight_quant=weight_quant
            )
            
    return model

def quantize_qwen_like(
    model, mlp_quant, self_attn_quant, low_bit, bit_layers, weight_quant="per_channel", quantize_bmm_input=False
):
    from transformers.models.qwen2.modeling_qwen2 import (
        Qwen2Attention,
        Qwen2MLP,
    )

    for name, m in model.model.named_modules():
        # print(name)
        if isinstance(m, Qwen2MLP):
            if low_bit == 0:
                continue
            else:
                if name in mlp_quant:
                    # bit = low_bit
                    layer_id = int(name.split('.')[1])
                    bit = bit_layers[layer_id]
                    print(f'{name} {bit} bit quant ')
                else:
                    bit = low_bit
                    print(f'{name} {bit} bit quant ')


            m.gate_proj = W8A16Linear.from_float(
                bit, m.gate_proj, weight_quant=weight_quant
            )
            m.up_proj = W8A16Linear.from_float(
                bit, m.up_proj, weight_quant=weight_quant
            )
            m.down_proj = W8A16Linear.from_float(
                bit, m.down_proj, weight_quant=weight_quant
            )
        elif isinstance(m, Qwen2Attention):
            if low_bit == 0:
                continue
            else:
                if name in self_attn_quant:
                    # bit = low_bit
                    layer_id = int(name.split('.')[1])
                    bit = bit_layers[layer_id]
                    print(f'{name} {bit} bit quant ')
                else:
                    bit = low_bit
                    print(f'{name} {bit} bit quant ')


            m.q_proj = W8A16Linear.from_float(
                bit,  
                m.q_proj,
                weight_quant=weight_quant,
                quantize_output=quantize_bmm_input,
            )
            m.k_proj = W8A16Linear.from_float(
                bit, 
                m.k_proj,
                weight_quant=weight_quant,
                quantize_output=quantize_bmm_input,
            )
            m.v_proj = W8A16Linear.from_float(
                bit, 
                m.v_proj,
                weight_quant=weight_quant,
                quantize_output=quantize_bmm_input,
            )
            m.o_proj = W8A16Linear.from_float(
                bit, m.o_proj, weight_quant=weight_quant
            )
            
    return model