Replace fp16 linear with quantized linear
(model, weight_bit_width, empty_init=False, device=None)
| 185 | |
| 186 | |
| 187 | def quantize(model, weight_bit_width, empty_init=False, device=None): |
| 188 | """Replace fp16 linear with quantized linear""" |
| 189 | for layer in model.layers: |
| 190 | layer.self_attention.query_key_value = QuantizedLinear( |
| 191 | weight_bit_width=weight_bit_width, |
| 192 | weight=layer.self_attention.query_key_value.weight, |
| 193 | bias=layer.self_attention.query_key_value.bias, |
| 194 | dtype=layer.self_attention.query_key_value.weight.dtype, |
| 195 | device=layer.self_attention.query_key_value.weight.device if device is None else device, |
| 196 | empty_init=empty_init |
| 197 | ) |
| 198 | layer.self_attention.dense = QuantizedLinear( |
| 199 | weight_bit_width=weight_bit_width, |
| 200 | weight=layer.self_attention.dense.weight, |
| 201 | bias=layer.self_attention.dense.bias, |
| 202 | dtype=layer.self_attention.dense.weight.dtype, |
| 203 | device=layer.self_attention.dense.weight.device if device is None else device, |
| 204 | empty_init=empty_init |
| 205 | ) |
| 206 | layer.mlp.dense_h_to_4h = QuantizedLinear( |
| 207 | weight_bit_width=weight_bit_width, |
| 208 | weight=layer.mlp.dense_h_to_4h.weight, |
| 209 | bias=layer.mlp.dense_h_to_4h.bias, |
| 210 | dtype=layer.mlp.dense_h_to_4h.weight.dtype, |
| 211 | device=layer.mlp.dense_h_to_4h.weight.device if device is None else device, |
| 212 | empty_init=empty_init |
| 213 | ) |
| 214 | layer.mlp.dense_4h_to_h = QuantizedLinear( |
| 215 | weight_bit_width=weight_bit_width, |
| 216 | weight=layer.mlp.dense_4h_to_h.weight, |
| 217 | bias=layer.mlp.dense_4h_to_h.bias, |
| 218 | dtype=layer.mlp.dense_4h_to_h.weight.dtype, |
| 219 | device=layer.mlp.dense_4h_to_h.weight.device if device is None else device, |
| 220 | empty_init=empty_init |
| 221 | ) |
| 222 | |
| 223 | return model |
| 224 | |
| 225 | |
| 226 |
no test coverage detected