Replace fp16 linear with quantized linear
(model, weight_bit_width)
| 235 | |
| 236 | |
| 237 | def quantize(model, weight_bit_width): |
| 238 | """Replace fp16 linear with quantized linear""" |
| 239 | |
| 240 | print_rank0(f"> Quantizing model weight to {weight_bit_width} bits") |
| 241 | |
| 242 | quantized_cnt = [0] # [] for tracing in closure |
| 243 | |
| 244 | def replace_linear(module): |
| 245 | for name, sub_module in module.named_children(): |
| 246 | if isinstance(sub_module, ColumnParallelLinear) and not isinstance(sub_module, QuantizedColumnParallelLinear): |
| 247 | setattr(module, name, QuantizedColumnParallelLinear( |
| 248 | weight_bit_width=weight_bit_width, |
| 249 | weight=sub_module.weight.to(torch.cuda.current_device()), |
| 250 | input_size=sub_module.input_size, |
| 251 | output_size=sub_module.output_size, |
| 252 | bias=hasattr(sub_module, 'bias') and isinstance(sub_module.bias, Parameter), |
| 253 | gather_output=sub_module.gather_output, |
| 254 | params_dtype=torch.half, |
| 255 | name=name, |
| 256 | skip_init=True, |
| 257 | device=sub_module.weight.device, |
| 258 | bias_val=getattr(sub_module, 'bias', None), |
| 259 | ) |
| 260 | ) |
| 261 | quantized_cnt[0] += sub_module.weight.numel() |
| 262 | |
| 263 | elif isinstance(sub_module, RowParallelLinear) and not isinstance(sub_module, QuantizedRowParallelLinear): |
| 264 | setattr(module, name, QuantizedRowParallelLinear( |
| 265 | weight_bit_width=weight_bit_width, |
| 266 | weight=sub_module.weight.to(torch.cuda.current_device()), |
| 267 | input_size=sub_module.input_size, |
| 268 | output_size=sub_module.output_size, |
| 269 | bias=hasattr(sub_module, 'bias') and isinstance(sub_module.bias, Parameter), |
| 270 | input_is_parallel=sub_module.input_is_parallel, |
| 271 | params_dtype=torch.half, |
| 272 | name=name, |
| 273 | skip_init=True, |
| 274 | device=sub_module.weight.device, |
| 275 | bias_val=getattr(sub_module, 'bias', None), |
| 276 | ) |
| 277 | ) |
| 278 | quantized_cnt[0] += sub_module.weight.numel() |
| 279 | else: |
| 280 | replace_linear(sub_module) |
| 281 | |
| 282 | replace_linear(model) |
| 283 | print_rank0(f"> Quantized {quantized_cnt[0]} parameters in total.") |
| 284 | |
| 285 | return model |
no test coverage detected