Given a 8-bit weight tensor containing values quantized to 4 bits, create a packed weight tensor by transposing the weight tensor, then packing 2 4-bit values in one 8-bit value. An input weight tensor of shape (N, K) will produce a packed weight tensor of shape (K, N / 2).
(weight_tensor: torch.Tensor)
| 291 | |
| 292 | |
| 293 | def pack_4bit_weight_tensor(weight_tensor: torch.Tensor) -> torch.Tensor: |
| 294 | """ |
| 295 | Given a 8-bit weight tensor containing values quantized to 4 bits, create a packed |
| 296 | weight tensor by transposing the weight tensor, then packing 2 4-bit values in one |
| 297 | 8-bit value. |
| 298 | |
| 299 | An input weight tensor of shape (N, K) will produce a packed weight tensor of shape |
| 300 | (K, N / 2). |
| 301 | """ |
| 302 | |
| 303 | # Assert we got a properly quantized tensor. |
| 304 | min_val, max_val = weight_tensor.min().item(), weight_tensor.max().item() |
| 305 | assert ( |
| 306 | max_val <= 7 and min_val >= -8 |
| 307 | ), f"pack_4bit_weight_tensor: [min_val,max_val] out of [-8, 7] range, got [{min_val}, {max_val}]" |
| 308 | |
| 309 | # Assuming we have a 2d tensor |
| 310 | if weight_tensor.ndim != 2: |
| 311 | weight_tensor = weight_tensor.squeeze() |
| 312 | assert ( |
| 313 | weight_tensor.ndim == 2 |
| 314 | ), f"pack_4bit_weight_tensor: expecting input tensor to be 2d, got {weight_tensor.ndim}" |
| 315 | |
| 316 | # Need to pad innermost dim to be a multiple of 8, since the minimum load granularity |
| 317 | # is int32 (4 bytes), which contains 8 4-bit values. |
| 318 | if weight_tensor.shape[-1] % 8 != 0: |
| 319 | num_pad = 8 - (weight_tensor.shape[-1] % 8) |
| 320 | weight_tensor = F.pad(input=weight_tensor, pad=(0, num_pad)) |
| 321 | |
| 322 | # Shape after padding |
| 323 | _, in_channels = weight_tensor.shape |
| 324 | assert in_channels % 8 == 0, "convert_to_qc4w: expecting ic to be divisible by 8" |
| 325 | |
| 326 | # Adjust weight_tensor tensor for zp |
| 327 | weight_tensor = weight_tensor.to(dtype=torch.uint8) + 8 |
| 328 | # Pack each 4-bit value into a single 8-bit value |
| 329 | return weight_tensor[::, 1::2] << 4 | weight_tensor[::, ::2] |
| 330 | |
| 331 | |
| 332 | def compute_per_group_sums(weight_tensor: torch.Tensor, group_size: int): |
no test coverage detected