| 65 | f"quantized tensor with {input.numel()} elements must be divisible by group_size {self.group_size}") |
| 66 | |
| 67 | def quantize(self, |
| 68 | input, |
| 69 | q_bits=8, |
| 70 | q_mantisa_bits=3, |
| 71 | stochastic_mode=False, |
| 72 | return_meta_tensor=False) -> torch.Tensor: |
| 73 | assert input.dtype == torch.bfloat16, "only support bf16 for now" |
| 74 | if return_meta_tensor: |
| 75 | assert q_bits == 8, "meta tensor is only supported with q_bit=8" |
| 76 | |
| 77 | self._validate_shape(input) |
| 78 | self.orig_dtype = input.dtype |
| 79 | self.orig_shape = input.shape |
| 80 | |
| 81 | if q_bits == 8: |
| 82 | pass |
| 83 | elif q_bits == 12: |
| 84 | q_mantisa_bits = 7 |
| 85 | elif q_bits == 6: |
| 86 | q_mantisa_bits = 2 |
| 87 | elif q_bits == 4: |
| 88 | q_mantisa_bits = 1 |
| 89 | else: |
| 90 | assert (0), \ |
| 91 | f"Missing {q_bits}-quantization, please add the template arguments for the kernel to support this precision!" |
| 92 | self.num_groups = input.numel() // self.group_size |
| 93 | self.input_q = torch.ones(self.num_groups, |
| 94 | int(self.group_size * q_bits) // 8 + 4, |
| 95 | dtype=torch.uint8, |
| 96 | device=input.device) |
| 97 | out = fp_quant_module.quantize(self.input_q, input, self.group_size, stochastic_mode, q_bits, q_mantisa_bits) |
| 98 | if return_meta_tensor: |
| 99 | data, self.scale = out.split(self.group_size, dim=-1) |
| 100 | data = data.contiguous().reshape(input.shape) |
| 101 | self.scale = self.scale.contiguous() |
| 102 | del self.input_q |
| 103 | del out |
| 104 | gc.collect() |
| 105 | get_accelerator().empty_cache() |
| 106 | return data, self.scale |
| 107 | |
| 108 | return out |
| 109 | |
| 110 | def to(self, *args, **kwargs): |
| 111 | # These start as None and are only allocated by quantize(). Moving the |