File size: 13,379 Bytes
f7eb3fa 57c2394 f7eb3fa 57c2394 f7eb3fa 57c2394 f7eb3fa 57c2394 f7eb3fa 57c2394 f7eb3fa 57c2394 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 | from __future__ import annotations
import torch
from ._ops import ops
__all__ = [
"matmul_packed_w4a4_int8",
"matmul_packed_adaln_int4_cpu",
"matmul_packed_weight",
"quantize_activations_cpu",
"quantize_activations_int8",
"quantize_activations_packed_w4",
"supports_cpu_activation",
"supports_cpu_adaln",
"supports_device",
]
def supports_device(device_type: str) -> bool:
dispatch_keys = {
"cpu": "CPU",
"cuda": "CUDA",
"mps": "MPS",
}
try:
dispatch_key = dispatch_keys[device_type]
except KeyError as exc:
raise ValueError(f"unknown device type {device_type!r}") from exc
return bool(
torch._C._dispatch_has_kernel_for_dispatch_key( # noqa: SLF001
ops.matmul_packed_weight._qualified_op_name, # noqa: SLF001
dispatch_key,
)
)
def supports_cpu_activation() -> bool:
try:
operation = ops.quantize_activations_cpu
qualified_name = operation._qualified_op_name # noqa: SLF001
except (AttributeError, RuntimeError):
return False
return bool(
torch._C._dispatch_has_kernel_for_dispatch_key( # noqa: SLF001
qualified_name,
"CPU",
)
)
def supports_cpu_adaln() -> bool:
try:
operation = ops.matmul_packed_adaln_int4_cpu
qualified_name = operation._qualified_op_name # noqa: SLF001
except (AttributeError, RuntimeError):
return False
return bool(
torch._C._dispatch_has_kernel_for_dispatch_key( # noqa: SLF001
qualified_name,
"CPU",
)
)
def quantize_activations_cpu(
x: torch.Tensor,
permutation: torch.Tensor,
signs: torch.Tensor,
centroids: torch.Tensor,
boundaries: torch.Tensor,
*,
eps: float,
inv_sqrt_block: float,
block_size: int,
) -> torch.Tensor:
if x.device.type != "cpu":
raise RuntimeError("native CPU activation quantization requires CPU tensors")
if x.dtype not in {torch.float32, torch.float16, torch.bfloat16}:
raise ValueError("x must be float32, float16, or bfloat16")
if block_size <= 0 or block_size & (block_size - 1):
raise ValueError("block_size must be a positive power of two")
dim = x.shape[-1]
if dim % block_size != 0:
raise ValueError("block_size must divide the input dimension")
original_shape = x.shape
values = x.contiguous().reshape(-1, dim)
out = torch.empty_like(values)
permutation_dtype = torch.int32 if permutation.dtype == torch.int32 else torch.int64
permutation_values = permutation.to(device="cpu", dtype=permutation_dtype).contiguous()
sign_values = signs.to(device="cpu", dtype=torch.int8).contiguous()
centroid_values = centroids.to(device="cpu", dtype=torch.float32).contiguous()
boundary_values = boundaries.to(device="cpu", dtype=torch.float32).contiguous()
ops.quantize_activations_cpu(
out,
values,
permutation_values,
sign_values,
centroid_values,
boundary_values,
eps,
inv_sqrt_block,
block_size,
)
return out.reshape(original_shape)
def matmul_packed_weight(
x: torch.Tensor,
packed_weight_indices: torch.Tensor,
row_norms: torch.Tensor,
centroids: torch.Tensor,
*,
bits: int,
out_features: int,
in_features: int,
bias: torch.Tensor | None = None,
block_m: int = 64,
block_n: int = 64,
block_k: int = 128,
) -> torch.Tensor:
if bits <= 0 or bits > 8:
raise ValueError("bits must be in [1, 8]")
if x.shape[-1] != in_features:
raise ValueError(f"expected input last dimension {in_features}, got {x.shape[-1]}")
if block_m <= 0 or block_n <= 0 or block_k <= 0:
raise ValueError("packed matmul tile sizes must be positive")
original_shape = x.shape
x_2d = x.contiguous().reshape(-1, in_features)
out = torch.empty((x_2d.shape[0], out_features), device=x.device, dtype=x.dtype)
packed = packed_weight_indices.to(device=x.device, dtype=torch.uint8).contiguous()
auxiliary_dtype = torch.bfloat16 if x.device.type == "cuda" else torch.float32
norms = row_norms.to(device=x.device, dtype=auxiliary_dtype).contiguous()
centroid_values = centroids.to(device=x.device, dtype=torch.float32).contiguous()
if bias is None:
bias_values = torch.empty((1,), device=x.device, dtype=torch.float32)
has_bias = False
else:
bias_dtype = x.dtype if x.device.type == "cuda" else torch.float32
bias_values = bias.to(device=x.device, dtype=bias_dtype).contiguous()
has_bias = True
ops.matmul_packed_weight(
out,
x_2d,
packed,
norms,
centroid_values,
bias_values,
has_bias,
bits,
out_features,
in_features,
block_m,
block_n,
block_k,
)
return out.reshape(*original_shape[:-1], out_features)
def matmul_packed_adaln_int4_cpu(
x: torch.Tensor,
packed_weight: torch.Tensor,
scales: torch.Tensor,
*,
out_features: int,
in_features: int,
group_size: int,
bias: torch.Tensor | None = None,
) -> torch.Tensor:
if x.device.type != "cpu":
raise RuntimeError("native packed AdaLN requires CPU tensors")
if x.shape[-1] != in_features:
raise ValueError(f"expected input last dimension {in_features}, got {x.shape[-1]}")
if group_size <= 0:
raise ValueError("group_size must be positive")
original_shape = x.shape
x_2d = x.to(dtype=torch.bfloat16).contiguous().reshape(-1, in_features)
out = torch.empty((x_2d.shape[0], out_features), dtype=torch.bfloat16)
packed = packed_weight.to(device="cpu", dtype=torch.uint8).contiguous()
scale_values = scales.to(device="cpu", dtype=torch.float32).contiguous()
if bias is None:
bias_values = torch.empty((1,), dtype=torch.float32)
has_bias = False
else:
bias_values = (
bias.to(device="cpu", dtype=torch.bfloat16).to(dtype=torch.float32).contiguous()
)
has_bias = True
ops.matmul_packed_adaln_int4_cpu(
out,
x_2d,
packed,
scale_values,
bias_values,
has_bias,
out_features,
in_features,
group_size,
)
return out.reshape(*original_shape[:-1], out_features)
def matmul_packed_w4a4_int8(
packed_activations: torch.Tensor,
packed_weight_indices: torch.Tensor,
token_norms: torch.Tensor,
row_norms: torch.Tensor,
activation_codes: torch.Tensor,
weight_codes: torch.Tensor,
*,
activation_scale: float,
weight_scale: float,
out_features: int,
in_features: int,
bias: torch.Tensor | None = None,
output_dtype: torch.dtype = torch.bfloat16,
tile_m: int = 128,
tile_n: int = 128,
async_packed: bool = False,
weight_k_major: bool = False,
) -> torch.Tensor:
if not packed_activations.is_cuda:
raise RuntimeError("packed W4A4 INT8 matmul requires CUDA tensors")
if in_features <= 0 or in_features % 64 != 0:
raise ValueError("in_features must be positive and divisible by 64")
if packed_activations.shape[-1] != in_features // 2:
raise ValueError(
f"expected packed activation last dimension {in_features // 2}, "
f"got {packed_activations.shape[-1]}"
)
if output_dtype not in {torch.float16, torch.bfloat16}:
raise ValueError("output_dtype must be float16 or bfloat16")
if (tile_m, tile_n) not in {(128, 128), (256, 128), (128, 256)}:
raise ValueError("tile must be 128x128, 256x128, or 128x256")
original_shape = packed_activations.shape
activations = (
packed_activations.to(dtype=torch.uint8).contiguous().reshape(-1, in_features // 2)
)
weights = packed_weight_indices.to(device=activations.device, dtype=torch.uint8).contiguous()
norms = token_norms.to(device=activations.device, dtype=torch.float32).contiguous()
weight_norms = row_norms.to(device=activations.device, dtype=torch.bfloat16).contiguous()
activation_code_values = activation_codes.to(
device=activations.device, dtype=torch.int8
).contiguous()
weight_code_values = weight_codes.to(device=activations.device, dtype=torch.int8).contiguous()
out = torch.empty(
(activations.shape[0], out_features),
device=activations.device,
dtype=output_dtype,
)
if bias is None:
bias_values = out
has_bias = False
else:
bias_values = bias.to(device=activations.device, dtype=output_dtype).contiguous()
has_bias = True
ops.matmul_packed_w4a4_int8(
out,
activations,
weights,
norms,
weight_norms,
activation_code_values,
weight_code_values,
bias_values,
has_bias,
activation_scale,
weight_scale,
out_features,
in_features,
tile_m,
tile_n,
async_packed,
weight_k_major,
)
return out.reshape(*original_shape[:-1], out_features)
def quantize_activations_packed_w4(
x: torch.Tensor,
permutation: torch.Tensor,
signs: torch.Tensor,
boundaries: torch.Tensor,
*,
eps: float = 1e-12,
inv_sqrt_block: float,
threads: int = 256,
) -> tuple[torch.Tensor, torch.Tensor]:
if not x.is_cuda:
raise RuntimeError("native packed W4 activation quantization requires CUDA tensors")
if x.dtype not in {torch.float16, torch.bfloat16}:
raise ValueError("x must be float16 or bfloat16")
dim = x.shape[-1]
if dim not in {512, 1024, 2048, 4096, 8192, 16384}:
raise ValueError(
"native packed W4 activation quantization supports dimensions "
"512, 1024, 2048, 4096, 8192, and 16384"
)
if threads not in {128, 256, 512}:
raise ValueError("threads must be 128, 256, or 512")
if permutation.numel() != dim or signs.numel() != dim:
raise ValueError("permutation and signs must match the input dimension")
if boundaries.numel() != 15:
raise ValueError("boundaries must contain 15 values")
original_shape = x.shape
values = x.contiguous().reshape(-1, dim)
packed = torch.empty((values.shape[0], dim // 2), device=x.device, dtype=torch.uint8)
norms = torch.empty(values.shape[0], device=x.device, dtype=torch.float32)
permutation_dtype = torch.int32 if permutation.dtype == torch.int32 else torch.int64
permutation_values = permutation.to(device=x.device, dtype=permutation_dtype).contiguous()
sign_values = signs.to(device=x.device, dtype=torch.int8).contiguous()
boundary_values = boundaries.to(device=x.device, dtype=torch.float32).contiguous()
ops.quantize_activations_packed_w4(
packed,
norms,
values,
permutation_values,
sign_values,
boundary_values,
eps,
inv_sqrt_block,
threads,
)
return (
packed.reshape(*original_shape[:-1], dim // 2),
norms.reshape(original_shape[:-1]),
)
def quantize_activations_int8(
x: torch.Tensor,
permutation: torch.Tensor,
signs: torch.Tensor,
boundaries: torch.Tensor,
codes: torch.Tensor,
*,
eps: float = 1e-12,
inv_sqrt_block: float,
threads: int = 256,
) -> tuple[torch.Tensor, torch.Tensor]:
if not x.is_cuda:
raise RuntimeError("native INT8 activation quantization requires CUDA tensors")
if x.dtype not in {torch.float16, torch.bfloat16}:
raise ValueError("x must be float16 or bfloat16")
dim = x.shape[-1]
if dim not in {512, 1024, 2048, 4096, 8192, 12288, 16384}:
raise ValueError(
"native INT8 activation quantization supports dimensions "
"512, 1024, 2048, 4096, 8192, 12288, and 16384"
)
if threads not in {128, 256, 512}:
raise ValueError("threads must be 128, 256, or 512")
if permutation.numel() != dim or signs.numel() != dim:
raise ValueError("permutation and signs must match the input dimension")
if boundaries.numel() != 15:
raise ValueError("boundaries must contain 15 values")
if codes.numel() != 16:
raise ValueError("codes must contain 16 values")
original_shape = x.shape
values = x.contiguous().reshape(-1, dim)
quantized = torch.empty(values.shape, device=x.device, dtype=torch.int8)
norms = torch.empty(values.shape[0], device=x.device, dtype=torch.float32)
permutation_dtype = torch.int32 if permutation.dtype == torch.int32 else torch.int64
permutation_values = permutation.to(device=x.device, dtype=permutation_dtype).contiguous()
sign_values = signs.to(device=x.device, dtype=torch.int8).contiguous()
boundary_values = boundaries.to(device=x.device, dtype=torch.float32).contiguous()
code_values = codes.to(device=x.device, dtype=torch.int8).contiguous()
ops.quantize_activations_int8(
quantized,
norms,
values,
permutation_values,
sign_values,
boundary_values,
code_values,
eps,
inv_sqrt_block,
threads,
)
return (
quantized.reshape(*original_shape[:-1], dim),
norms.reshape(original_shape[:-1]),
)
|