Quantize a tensor using per-tensor static scaling factor. Args: tensor: The input tensor. dtype: The data type to quantize to.
(tensor: torch.Tensor, dtype: torch.dtype)
| 214 | return tokens |
| 215 | |
| 216 | def per_tensor_quantize(tensor: torch.Tensor, dtype: torch.dtype) -> Tuple[torch.Tensor, torch.Tensor]: |
| 217 | """Quantize a tensor using per-tensor static scaling factor. |
| 218 | Args: |
| 219 | tensor: The input tensor. |
| 220 | dtype: The data type to quantize to. |
| 221 | """ |
| 222 | finfo = torch.finfo(dtype) |
| 223 | # Calculate the scale as dtype max divided by absmax. |
| 224 | # Since .abs() creates a new tensor, we use aminmax to get |
| 225 | # the min and max first and then calculate the absmax. |
| 226 | if tensor.numel() == 0: |
| 227 | # Deal with empty tensors (triggered by empty MoE experts) |
| 228 | min_val, max_val = ( |
| 229 | torch.tensor(-16.0, dtype=tensor.dtype), |
| 230 | torch.tensor(16.0, dtype=tensor.dtype), |
| 231 | ) |
| 232 | else: |
| 233 | min_val, max_val = tensor.aminmax() |
| 234 | amax = torch.maximum(min_val.abs(), max_val.abs()) |
| 235 | scale = finfo.max / amax.clamp(min=1e-12) |
| 236 | # scale and clamp the tensor to bring it to |
| 237 | # the representative range of float8 data type |
| 238 | # (as default cast is unsaturated) |
| 239 | qweight = (tensor * scale).clamp(min=finfo.min, max=finfo.max) |
| 240 | # Return both float8 data and the inverse scale (as float), |
| 241 | # as both required as inputs to torch._scaled_mm |
| 242 | qweight = qweight.to(dtype) |
| 243 | scale = scale.float().reciprocal() |
| 244 | return qweight, scale |
| 245 | |
| 246 | def per_tensor_dequantize(qweight: torch.Tensor, scale: torch.Tensor) -> torch.Tensor: |
| 247 | assert scale.numel() == 1 |
no outgoing calls
no test coverage detected