| 199 | |
| 200 | |
| 201 | def quant_naive_inplace(w, dtype): |
| 202 | if w.dim() != 2: |
| 203 | raise ValueError(f"Only 2D tensors supported. Got {w.dim()}D tensor") |
| 204 | if torch.isnan(w).any(): |
| 205 | raise ValueError("Tensor contains NaN values") |
| 206 | |
| 207 | org_w_shape = w.shape |
| 208 | max_val = w.abs().amax(dim=1, keepdim=True).clamp(min=1e-5) |
| 209 | if dtype == torch.float8_e4m3fn: |
| 210 | finfo = torch.finfo(dtype) |
| 211 | qmin, qmax = finfo.min, finfo.max |
| 212 | elif dtype == torch.int8: |
| 213 | qmin, qmax = -128, 127 |
| 214 | else: |
| 215 | raise ValueError(f"Unsupported dtype: {dtype}") |
| 216 | |
| 217 | scales = max_val / qmax |
| 218 | w.div_(scales) |
| 219 | w.clamp_(qmin, qmax) |
| 220 | |
| 221 | if dtype == torch.int8: |
| 222 | w.round_() |
| 223 | w = w.to(dtype) |
| 224 | assert torch.isnan(scales).sum() == 0, "Scales contains NaN" |
| 225 | assert torch.isnan(w).sum() == 0, "Quantized tensor contains NaN" |
| 226 | |
| 227 | scales = scales.view(org_w_shape[0], -1) |
| 228 | w = w.view(org_w_shape) |
| 229 | return w, scales |
| 230 | |
| 231 | |
| 232 | def dequant_naive_inplace(input_tensor, input_tensor_scale, dtype): |