diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7cb3582e120f991fdab0f8d65bd2d996acd47d6 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/__pycache__/api.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/__pycache__/api.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cea6c9719094e9eca3d10efe0b6b568a0889bfcd Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/__pycache__/api.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/__pycache__/utils.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa57ddc5d99bfd6eddb48033afedeca598e8d375 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/__pycache__/utils.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/fp8_fa3/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/fp8_fa3/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4a4487f0435dd2197a2386c696d2966b7e3c25e8 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/fp8_fa3/__init__.py @@ -0,0 +1,21 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +""" +FP8 attention using FA3 backend. +""" + +from torchao.prototype.attention.fp8_fa3.attention import ( + fp8_fa3_rope_sdpa, + fp8_fa3_sdpa, +) +from torchao.prototype.attention.quantization import _fp8_sdpa_quantize + +__all__ = [ + "fp8_fa3_sdpa", + "fp8_fa3_rope_sdpa", + "_fp8_sdpa_quantize", +] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/fp8_fa3/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/fp8_fa3/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..192b06f4069a6bfd234a873b1360846b7945c1a4 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/fp8_fa3/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/fp8_fa3/__pycache__/attention.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/fp8_fa3/__pycache__/attention.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c12491aa6dffb0873e03da27c56bb775bf460fa8 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/fp8_fa3/__pycache__/attention.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/fp8_fa3/__pycache__/setup.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/fp8_fa3/__pycache__/setup.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b2f94178a93e31b4ea13fe47cf606409a971bac Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/fp8_fa3/__pycache__/setup.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/fp8_fa3/attention.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/fp8_fa3/attention.py new file mode 100644 index 0000000000000000000000000000000000000000..60c9b9f8784d2435ea398d8f31c8511430167dd4 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/fp8_fa3/attention.py @@ -0,0 +1,44 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +""" +FP8 SDPA using FA3 backend. + +When using these functions directly (not through apply_low_precision_attention), +you must activate FA3 yourself:: + + activate_flash_attention_impl("FA3") + try: + out = fp8_fa3_sdpa(q, k, v, is_causal=True) + finally: + restore_flash_attention_impl() +""" + +from functools import partial + +from torchao.prototype.attention.shared_utils.attention import ( + _fp8_rope_sdpa, + _fp8_sdpa, +) +from torchao.prototype.attention.shared_utils.custom_ops import ( + register_fp8_attention_ops, +) + +fp8_fa3_sdpa = partial(_fp8_sdpa, backend_name="FA3") +fp8_fa3_sdpa.__doc__ = _fp8_sdpa.__doc__ +fp8_fa3_sdpa.__name__ = "fp8_fa3_sdpa" +fp8_fa3_sdpa.__qualname__ = "fp8_fa3_sdpa" + +fp8_fa3_rope_sdpa = partial(_fp8_rope_sdpa, backend_name="FA3") +fp8_fa3_rope_sdpa.__doc__ = _fp8_rope_sdpa.__doc__ +fp8_fa3_rope_sdpa.__name__ = "fp8_fa3_rope_sdpa" +fp8_fa3_rope_sdpa.__qualname__ = "fp8_fa3_rope_sdpa" + +_ops = register_fp8_attention_ops( + backend_name="fa3", + rope_sdpa_fn=fp8_fa3_rope_sdpa, + sdpa_fn=fp8_fa3_sdpa, +) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/fp8_fa3/setup.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/fp8_fa3/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..d9849c7b1e43fc15fe92d48d9ae41e9820900c96 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/fp8_fa3/setup.py @@ -0,0 +1,27 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +"""FP8 FA3 backend setup.""" + +import torch.nn as nn + +from torchao.prototype.attention.config import LowPrecisionAttentionConfig +from torchao.prototype.attention.shared_utils.setup import setup_fp8_backend + + +def setup_fp8_fa3( + model: nn.Module, + config: LowPrecisionAttentionConfig, +) -> nn.Module: + """Set up FP8 FA3 attention on *model* and wrap it.""" + from torchao.prototype.attention.fp8_fa3.attention import fp8_fa3_sdpa + + return setup_fp8_backend( + model, + config, + flash_impl_name="FA3", + sdpa_fn=fp8_fa3_sdpa, + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..945a52bfc1b0855dfca30aa0bc085b76721d01df --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/__init__.py @@ -0,0 +1,17 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +from torchao.prototype.attention.quantization.triton_qkv_quantization import ( + triton_fp8_sdpa_quantize as _fp8_sdpa_quantize, +) +from torchao.prototype.attention.quantization.triton_rope_qkv_quantization import ( + triton_fp8_rope_sdpa_quantize as _fp8_rope_sdpa_quantize, +) + +__all__ = [ + "_fp8_sdpa_quantize", + "_fp8_rope_sdpa_quantize", +] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e0302aab5584d474a5cf956d4eeafd2dc9cd2da Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/__pycache__/quantization.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/__pycache__/quantization.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4e2c33251789098d5816094fdf935887b07d53c Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/__pycache__/quantization.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/__pycache__/triton_qkv_quantization.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/__pycache__/triton_qkv_quantization.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ecfb09c7e60e39966c3db308103b1000071cd83d Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/__pycache__/triton_qkv_quantization.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/__pycache__/triton_rope_qkv_quantization.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/__pycache__/triton_rope_qkv_quantization.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0892cbfedf7dfe9ad247a777f1f8124a5c1e16dc Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/__pycache__/triton_rope_qkv_quantization.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/quantization.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/quantization.py new file mode 100644 index 0000000000000000000000000000000000000000..84a255ead788759841d190d0626d52dda4c43015 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/quantization.py @@ -0,0 +1,50 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +""" +FP8 quantization for attention inputs. +""" + +from typing import Tuple + +import torch + + +def _fp8_sdpa_quantize( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, +) -> Tuple[ + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, +]: + """Quantize Q, K, V to FP8 with per-head scaling.""" + if q.dim() != 4: + raise ValueError(f"Expected 4D tensor for q, got {q.dim()}D") + if k.dim() != 4: + raise ValueError(f"Expected 4D tensor for k, got {k.dim()}D") + if v.dim() != 4: + raise ValueError(f"Expected 4D tensor for v, got {v.dim()}D") + if k.shape != v.shape: + raise ValueError(f"K and V shape mismatch: {k.shape} vs {v.shape}") + if q.shape[0] != k.shape[0]: + raise ValueError(f"Batch size mismatch: {q.shape[0]} vs {k.shape[0]}") + if q.shape[1] % k.shape[1] != 0: + raise ValueError( + f"Q head count ({q.shape[1]}) must be a multiple of K head count ({k.shape[1]})" + ) + if q.shape[3] != k.shape[3]: + raise ValueError(f"Head dim mismatch: {q.shape[3]} vs {k.shape[3]}") + + from torchao.prototype.attention.quantization.triton_qkv_quantization import ( + triton_fp8_sdpa_quantize, + ) + + return triton_fp8_sdpa_quantize(q, k, v) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/triton_qkv_quantization.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/triton_qkv_quantization.py new file mode 100644 index 0000000000000000000000000000000000000000..d2fe4df329e7e649d85604774113c3614bc476aa --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/triton_qkv_quantization.py @@ -0,0 +1,474 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +""" +FP8 quantization kernels for Q, K, V. + +Input/output format: [B, H, S, D]. +Supports GQA (different head counts for Q vs K/V). +""" + +from typing import Optional, Tuple + +import torch +import triton +import triton.language as tl + + +def _compute_num_chunks(tensor: torch.Tensor, S: int) -> int: + """Compute optimal number of chunks based on GPU properties.""" + props = torch.cuda.get_device_properties(tensor.device) + num_sms = props.multi_processor_count + B, H = tensor.shape[:2] # [B, H, S, D] + base_parallelism = B * H + # Target 2-4x SMs for good occupancy/latency hiding + target_blocks = num_sms * 4 + num_chunks = max(1, target_blocks // base_parallelism) + # Ensure each chunk has at least 32 S positions for efficiency + num_chunks = min(num_chunks, S // 32) if S >= 32 else 1 + # Cap at reasonable maximum + num_chunks = min(num_chunks, 64) + # Adjust if S is small + num_chunks = min(num_chunks, S) + return num_chunks + + +@triton.autotune( + configs=[ + triton.Config({"BLOCK_SIZE": 512}, num_warps=4), + triton.Config({"BLOCK_SIZE": 1024}, num_warps=4), + triton.Config({"BLOCK_SIZE": 2048}, num_warps=8), + triton.Config({"BLOCK_SIZE": 4096}, num_warps=8), + ], + key=["chunk_size", "D"], +) +@triton.jit +def single_phase1_kernel( + # Input tensor [B, H, S, D] + x_ptr, + # Output: partial max values [B * H * num_chunks] + partial_max_ptr, + # Input strides (for [B, H, S, D] layout) + stride_b, + stride_h, + stride_s, + stride_d, + # Dimensions + S, + D, + H, + chunk_size, + num_chunks, + # Block size + BLOCK_SIZE: tl.constexpr, +): + """ + Phase 1 for a single tensor: Compute partial absmax. + + Grid: (B, H, num_chunks) + + Uses linearized iteration over chunk_size * D elements. + """ + pid_b = tl.program_id(axis=0) + pid_h = tl.program_id(axis=1) + pid_chunk = tl.program_id(axis=2) + + # Compute the S range for this chunk + s_start = pid_chunk * chunk_size + s_end = tl.minimum(s_start + chunk_size, S) + chunk_elements = (s_end - s_start) * D + + # Base pointer for input [B, H, S, D] + base_offset = pid_b * stride_b + pid_h * stride_h + + # Initialize max accumulator + x_max = 0.0 + + # Linearized iteration over chunk_size * D elements + for block_start in range(0, chunk_elements, BLOCK_SIZE): + offs = block_start + tl.arange(0, BLOCK_SIZE) + mask = offs < chunk_elements + + # Convert linear offset to (s, d) coordinates + local_s = offs // D + d_idx = offs % D + s_idx = s_start + local_s + + # Input offset [B, H, S, D] + ptr_offset = s_idx * stride_s + d_idx * stride_d + + x_val = tl.load(x_ptr + base_offset + ptr_offset, mask=mask, other=0.0).to( + tl.float32 + ) + x_max = tl.maximum(x_max, tl.max(tl.abs(x_val))) + + # Store partial max + chunk_idx = pid_b * (H * num_chunks) + pid_h * num_chunks + pid_chunk + tl.store(partial_max_ptr + chunk_idx, x_max) + + +@triton.jit +def single_reduce_kernel( + partial_max_ptr, # [B * H * num_chunks] + scale_ptr, + descale_ptr, + H, + num_chunks, +): + """ + Reduce partial maxes and compute scale/descale for a single tensor. + + Grid: (B, H) + """ + pid_b = tl.program_id(axis=0) + pid_h = tl.program_id(axis=1) + + # Reduce across chunks for this (batch, head) + x_max = 0.0 + + base_idx = (pid_b * H + pid_h) * num_chunks + for c in range(num_chunks): + x_max = tl.maximum(x_max, tl.load(partial_max_ptr + base_idx + c)) + + # Compute scale and descale + # FP8 E4M3 max value is 448.0 + FP8_MAX = 448.0 + eps = 1e-12 + scale_idx = pid_b * H + pid_h + + tl.store(scale_ptr + scale_idx, tl.where(x_max > eps, FP8_MAX / x_max, 1.0)) + tl.store(descale_ptr + scale_idx, tl.where(x_max > eps, x_max / FP8_MAX, 1.0)) + + +@triton.jit +def group_reduce_kernel( + partial_max_ptr, # [B * H_q * num_chunks] + scale_ptr, # [B, H_kv] + descale_ptr, # [B, H_kv] + H_q, + H_kv, + groups, # H_q // H_kv + num_chunks, +): + """ + Reduce partial maxes across head groups for GQA Q tensor. + + For each KV group, reduces the max across all Q heads in that group + and all chunks, producing one scale per (batch, kv_head). + + Grid: (B, H_kv) + """ + pid_b = tl.program_id(axis=0) + pid_hkv = tl.program_id(axis=1) + + x_max = 0.0 + + for g in range(groups): + h_q = pid_hkv * groups + g + base_idx = (pid_b * H_q + h_q) * num_chunks + for c in range(num_chunks): + x_max = tl.maximum(x_max, tl.load(partial_max_ptr + base_idx + c)) + + FP8_MAX = 448.0 + eps = 1e-12 + scale_idx = pid_b * H_kv + pid_hkv + + tl.store(scale_ptr + scale_idx, tl.where(x_max > eps, FP8_MAX / x_max, 1.0)) + tl.store(descale_ptr + scale_idx, tl.where(x_max > eps, x_max / FP8_MAX, 1.0)) + + +@triton.autotune( + configs=[ + triton.Config({"BLOCK_SIZE": 512}, num_warps=4), + triton.Config({"BLOCK_SIZE": 1024}, num_warps=4), + triton.Config({"BLOCK_SIZE": 2048}, num_warps=8), + triton.Config({"BLOCK_SIZE": 4096}, num_warps=8), + ], + key=["chunk_size", "D"], +) +@triton.jit +def single_phase2_kernel( + # Input tensor [B, H, S, D] + x_ptr, + # Output tensor [B, H, S, D] - FP8 quantized + x_out_ptr, + # Precomputed scale [B, H_scale] + scale_ptr, + # Strides (for [B, H, S, D] layout) + stride_b, + stride_h, + stride_s, + stride_d, + # Dimensions + S, + D, + H, + chunk_size, + # Scale indexing for GQA: scale has H_scale entries per batch, + # and each group of `groups` heads shares one scale. + # For non-GQA: H_scale = H, groups = 1. + H_scale, + groups, + # Block size + BLOCK_SIZE: tl.constexpr, +): + """ + Phase 2 for a single tensor: Quantize to FP8 using precomputed scale. + + Grid: (B, H, num_chunks) + """ + pid_b = tl.program_id(axis=0) + pid_h = tl.program_id(axis=1) + pid_chunk = tl.program_id(axis=2) + + # Load scale for this head (or head group for GQA) + scale = tl.load(scale_ptr + pid_b * H_scale + pid_h // groups) + + # Compute the S range for this chunk + s_start = pid_chunk * chunk_size + s_end = tl.minimum(s_start + chunk_size, S) + chunk_elements = (s_end - s_start) * D + + # Base pointer + base_offset = pid_b * stride_b + pid_h * stride_h + + # Linearized iteration over chunk_size * D elements + for block_start in range(0, chunk_elements, BLOCK_SIZE): + offs = block_start + tl.arange(0, BLOCK_SIZE) + mask = offs < chunk_elements + + # Convert linear offset to (s, d) coordinates + local_s = offs // D + d_idx = offs % D + s_idx = s_start + local_s + + ptr_offset = base_offset + s_idx * stride_s + d_idx * stride_d + + # Load input value + x_val = tl.load(x_ptr + ptr_offset, mask=mask, other=0.0).to(tl.float32) + + # Quantize to FP8 + x_fp8 = (x_val * scale).to(tl.float8e4nv) + + # Store to output + tl.store(x_out_ptr + ptr_offset, x_fp8, mask=mask) + + +def triton_fp8_sdpa_quantize( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + num_chunks: Optional[int] = None, +) -> Tuple[ + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, +]: + """ + Separated FP8 quantization for Q, K, V tensors. + + Quantizes all tensors to FP8 with per-head scaling. + Each of Q, K, V is processed with independent kernel launches, + supporting GQA where Q has more heads than K/V (H_q = groups * H_kv) + and cross-attention where Q and K/V have different sequence lengths. + + For GQA, Q is quantized with per-KV-group scaling so that q_descale + has shape [B, H_kv] as required by FA3. + + Args: + q: Query tensor of shape [B, H_q, S_q, D] in bf16/fp16 + k: Key tensor of shape [B, H_kv, S_kv, D] in bf16/fp16 + v: Value tensor of shape [B, H_kv, S_kv, D] in bf16/fp16 + num_chunks: Number of chunks to split the S dimension into. + If None, automatically selects based on GPU SM count. + + Returns: + q_fp8: Quantized query, shape [B, H_q, S_q, D] in fp8 + k_fp8: Quantized key, shape [B, H_kv, S_kv, D] in fp8 + v_fp8: Quantized value, shape [B, H_kv, S_kv, D] in fp8 + q_descale: Query descale factors, shape [B, H_kv] in fp32 + k_descale: Key descale factors, shape [B, H_kv] in fp32 + v_descale: Value descale factors, shape [B, H_kv] in fp32 + """ + assert q.dim() == 4, f"Expected 4D tensor [B, H, S, D], got {q.dim()}D" + assert k.dim() == 4, f"Expected 4D tensor [B, H, S, D], got {k.dim()}D" + assert v.dim() == 4, f"Expected 4D tensor [B, H, S, D], got {v.dim()}D" + assert k.shape == v.shape, ( + f"K and V must have the same shape, got {k.shape} vs {v.shape}" + ) + assert q.shape[0] == k.shape[0], ( + f"Batch size mismatch: {q.shape[0]} vs {k.shape[0]}" + ) + assert q.shape[3] == k.shape[3], f"Head dim mismatch: {q.shape[3]} vs {k.shape[3]}" + assert q.shape[1] % k.shape[1] == 0, ( + f"Q heads ({q.shape[1]}) must be a multiple of K heads ({k.shape[1]})" + ) + + B, H_q, S_q, D = q.shape + H_kv = k.shape[1] + S_kv = k.shape[2] + groups = H_q // H_kv + + # Make tensors contiguous if needed + q = q.contiguous() + k = k.contiguous() + v = v.contiguous() + + # Compute number of chunks independently for Q and KV + if num_chunks is None: + q_num_chunks = _compute_num_chunks(q, S_q) + kv_num_chunks = _compute_num_chunks(k, S_kv) + else: + q_num_chunks = num_chunks + kv_num_chunks = num_chunks + q_chunk_size = (S_q + q_num_chunks - 1) // q_num_chunks + kv_chunk_size = (S_kv + kv_num_chunks - 1) // kv_num_chunks + + # Allocate output tensors + q_fp8 = torch.empty_like(q, dtype=torch.float8_e4m3fn) + k_fp8 = torch.empty_like(k, dtype=torch.float8_e4m3fn) + v_fp8 = torch.empty_like(v, dtype=torch.float8_e4m3fn) + + # Allocate partial max buffers (one per tensor) + q_partial_max = torch.empty( + B * H_q * q_num_chunks, dtype=torch.float32, device=q.device + ) + k_partial_max = torch.empty( + B * H_kv * kv_num_chunks, dtype=torch.float32, device=q.device + ) + v_partial_max = torch.empty( + B * H_kv * kv_num_chunks, dtype=torch.float32, device=q.device + ) + + # Allocate scale/descale tensors. + # For GQA, Q scale/descale are [B, H_kv] (per KV group). + # K and V are always [B, H_kv] (per head). + q_scale = torch.empty(B, H_kv, dtype=torch.float32, device=q.device) + k_scale = torch.empty(B, H_kv, dtype=torch.float32, device=q.device) + v_scale = torch.empty(B, H_kv, dtype=torch.float32, device=q.device) + q_descale = torch.empty(B, H_kv, dtype=torch.float32, device=q.device) + k_descale = torch.empty(B, H_kv, dtype=torch.float32, device=q.device) + v_descale = torch.empty(B, H_kv, dtype=torch.float32, device=q.device) + + q_grid_chunked = (B, H_q, q_num_chunks) + kv_grid_chunked = (B, H_kv, kv_num_chunks) + + # ---- Phase 1: Max for Q ---- + single_phase1_kernel[q_grid_chunked]( + q, + q_partial_max, + q.stride(0), + q.stride(1), + q.stride(2), + q.stride(3), + S_q, + D, + H_q, + q_chunk_size, + q_num_chunks, + ) + + # ---- Phase 1: Max for K ---- + single_phase1_kernel[kv_grid_chunked]( + k, + k_partial_max, + k.stride(0), + k.stride(1), + k.stride(2), + k.stride(3), + S_kv, + D, + H_kv, + kv_chunk_size, + kv_num_chunks, + ) + + # ---- Phase 1: Max for V ---- + single_phase1_kernel[kv_grid_chunked]( + v, + v_partial_max, + v.stride(0), + v.stride(1), + v.stride(2), + v.stride(3), + S_kv, + D, + H_kv, + kv_chunk_size, + kv_num_chunks, + ) + + # ---- Reduce ---- + # Q: group reduce across `groups` Q heads per KV head + group_reduce_kernel[(B, H_kv)]( + q_partial_max, q_scale, q_descale, H_q, H_kv, groups, q_num_chunks + ) + # K, V: per-head reduce + single_reduce_kernel[(B, H_kv)]( + k_partial_max, k_scale, k_descale, H_kv, kv_num_chunks + ) + single_reduce_kernel[(B, H_kv)]( + v_partial_max, v_scale, v_descale, H_kv, kv_num_chunks + ) + + # ---- Phase 2: Quantize Q ---- + # Q scale is [B, H_kv]; each group of `groups` Q heads shares one scale. + single_phase2_kernel[q_grid_chunked]( + q, + q_fp8, + q_scale, + q.stride(0), + q.stride(1), + q.stride(2), + q.stride(3), + S_q, + D, + H_q, + q_chunk_size, + H_kv, + groups, + ) + + # ---- Phase 2: Quantize K ---- + # K scale is [B, H_kv]; groups=1 (per-head). + single_phase2_kernel[kv_grid_chunked]( + k, + k_fp8, + k_scale, + k.stride(0), + k.stride(1), + k.stride(2), + k.stride(3), + S_kv, + D, + H_kv, + kv_chunk_size, + H_kv, + 1, + ) + + # ---- Phase 2: Quantize V ---- + # V scale is [B, H_kv]; groups=1 (per-head). + single_phase2_kernel[kv_grid_chunked]( + v, + v_fp8, + v_scale, + v.stride(0), + v.stride(1), + v.stride(2), + v.stride(3), + S_kv, + D, + H_kv, + kv_chunk_size, + H_kv, + 1, + ) + + return q_fp8, k_fp8, v_fp8, q_descale, k_descale, v_descale diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/triton_rope_qkv_quantization.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/triton_rope_qkv_quantization.py new file mode 100644 index 0000000000000000000000000000000000000000..6ec95dd5afad748ca3822f520eed251d9858e859 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/triton_rope_qkv_quantization.py @@ -0,0 +1,745 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +""" +Fused RoPE + FP8 quantization kernels for Q, K, V. + +Input: [B, S, H, D], output: [B, H, S, D]. +Supports GQA (different head counts for Q vs K/V). +""" + +from typing import Optional, Tuple + +import torch +import triton +import triton.language as tl + + +def _compute_num_chunks(tensor: torch.Tensor, S: int) -> int: + """Compute optimal number of chunks based on GPU properties.""" + props = torch.cuda.get_device_properties(tensor.device) + num_sms = props.multi_processor_count + B, _, H, _ = tensor.shape # [B, S, H, D] + base_parallelism = B * H + # Target 2-4x SMs for good occupancy/latency hiding + target_blocks = num_sms * 4 + num_chunks = max(1, target_blocks // base_parallelism) + # Ensure each chunk has at least 32 S positions for efficiency + num_chunks = min(num_chunks, S // 32) if S >= 32 else 1 + # Cap at reasonable maximum + num_chunks = min(num_chunks, 64) + # Adjust if S is small + num_chunks = min(num_chunks, S) + return num_chunks + + +@triton.autotune( + configs=[ + triton.Config({"BLOCK_SIZE": 256}, num_warps=4), + triton.Config({"BLOCK_SIZE": 512}, num_warps=4), + triton.Config({"BLOCK_SIZE": 1024}, num_warps=8), + triton.Config({"BLOCK_SIZE": 2048}, num_warps=8), + ], + key=["chunk_size", "D_HALF"], +) +@triton.jit +def rope_single_phase1_kernel( + # Input tensor [B, S, H, D] + x_ptr, + # RoPE frequency tensors [S, D] + cos_ptr, + sin_ptr, + # Intermediate output tensor [B, H, S, D] - stores RoPE'd result + x_rope_ptr, + # Output: partial max values [B * H * num_chunks] + partial_max_ptr, + # Input strides (for [B, S, H, D] layout) + stride_in_b, + stride_in_s, + stride_in_h, + stride_in_d, + # Output strides (for [B, H, S, D] layout) + stride_out_b, + stride_out_h, + stride_out_s, + stride_out_d, + # Dimensions + S, + D, + D_HALF, + H, + chunk_size, + num_chunks, + # Block size + BLOCK_SIZE: tl.constexpr, + ROPE_INTERLEAVED: tl.constexpr, +): + """ + Phase 1 for a single tensor (Q or K): Apply RoPE, store to intermediate, + compute partial max. + + Grid: (B, H, num_chunks) + + Supports two RoPE pairing variants (selected by ROPE_INTERLEAVED constexpr): + - NeoX half-split (ROPE_INTERLEAVED=False): pairs (j, j+D/2) for j in [0, D/2) + - Interleaved (ROPE_INTERLEAVED=True): pairs (2i, 2i+1) for i in [0, D/2) + + Each pair shares the same rotation angle and the 2D rotation formula is: + out[first] = x[first]*cos - x[second]*sin + out[second] = x[second]*cos + x[first]*sin + """ + pid_b = tl.program_id(axis=0) + pid_h = tl.program_id(axis=1) + pid_chunk = tl.program_id(axis=2) + + # Compute the S range for this chunk + s_start = pid_chunk * chunk_size + s_end = tl.minimum(s_start + chunk_size, S) + actual_chunk_size = s_end - s_start + + # Number of pairs to process in this chunk + chunk_pairs = actual_chunk_size * D_HALF + + # Base pointers for input [B, S, H, D] + in_base_b = pid_b * stride_in_b + in_base_h = pid_h * stride_in_h + + # Base pointers for output [B, H, S, D] + out_base_b = pid_b * stride_out_b + out_base_h = pid_h * stride_out_h + + # Initialize max accumulator + x_max = 0.0 + + # Linearized iteration over chunk_size * D_HALF pairs + for block_start in range(0, chunk_pairs, BLOCK_SIZE): + offs = block_start + tl.arange(0, BLOCK_SIZE) + mask = offs < chunk_pairs + + # Convert linear offset to (s, pair_idx) coordinates + local_s = offs // D_HALF + pair_idx = offs % D_HALF + s_idx = s_start + local_s + + # Compute element indices for this pair based on RoPE variant + if ROPE_INTERLEAVED: + # FLUX/GPT-J interleaved: pair (2i, 2i+1) + d_first = pair_idx * 2 + d_second = pair_idx * 2 + 1 + else: + # NeoX/LLaMA half-split: pair (j, j+D/2) + d_first = pair_idx + d_second = pair_idx + D_HALF + + # Input offsets [B, S, H, D] + in_offset_first = ( + in_base_b + s_idx * stride_in_s + in_base_h + d_first * stride_in_d + ) + in_offset_second = ( + in_base_b + s_idx * stride_in_s + in_base_h + d_second * stride_in_d + ) + + # Output offsets [B, H, S, D] + out_offset_first = ( + out_base_b + out_base_h + s_idx * stride_out_s + d_first * stride_out_d + ) + out_offset_second = ( + out_base_b + out_base_h + s_idx * stride_out_s + d_second * stride_out_d + ) + + # Load input pairs (each element loaded exactly once) + x_first = tl.load(x_ptr + in_offset_first, mask=mask, other=0.0).to(tl.float32) + x_second = tl.load(x_ptr + in_offset_second, mask=mask, other=0.0).to( + tl.float32 + ) + + # Load cos/sin — both elements in a NeoX pair share the same + # rotation angle. cos[j] == cos[j+D/2] in LLaMA's frequency + # layout, so we only need one load per pair. + cos_offset = s_idx * D + d_first + cos_val = tl.load(cos_ptr + cos_offset, mask=mask, other=1.0).to(tl.float32) + sin_val = tl.load(sin_ptr + cos_offset, mask=mask, other=0.0).to(tl.float32) + + # Apply NeoX RoPE rotation: + # out[j] = x[j] * cos - x[j+D/2] * sin + # out[j+D/2] = x[j+D/2] * cos + x[j] * sin + x_rope_first = tl.math.fma(x_first, cos_val, -(x_second * sin_val)) + x_rope_second = tl.math.fma(x_second, cos_val, x_first * sin_val) + + # Store RoPE'd result to intermediate buffer [B, H, S, D] + tl.store( + x_rope_ptr + out_offset_first, x_rope_first.to(x_first.dtype), mask=mask + ) + tl.store( + x_rope_ptr + out_offset_second, x_rope_second.to(x_first.dtype), mask=mask + ) + + # Update max values (from RoPE'd values) + x_max = tl.maximum(x_max, tl.max(tl.abs(x_rope_first))) + x_max = tl.maximum(x_max, tl.max(tl.abs(x_rope_second))) + + # Store partial max + chunk_idx = pid_b * (H * num_chunks) + pid_h * num_chunks + pid_chunk + tl.store(partial_max_ptr + chunk_idx, x_max) + + +@triton.autotune( + configs=[ + triton.Config({"BLOCK_SIZE": 512}, num_warps=4), + triton.Config({"BLOCK_SIZE": 1024}, num_warps=4), + triton.Config({"BLOCK_SIZE": 2048}, num_warps=8), + triton.Config({"BLOCK_SIZE": 4096}, num_warps=8), + ], + key=["chunk_size", "D"], +) +@triton.jit +def v_phase1_kernel( + # Input tensor [B, S, H, D] + v_ptr, + # Output: partial max values [B * H * num_chunks] + partial_max_ptr, + # Input strides (for [B, S, H, D] layout) + stride_in_b, + stride_in_s, + stride_in_h, + stride_in_d, + # Dimensions + S, + D, + H, + chunk_size, + num_chunks, + # Block size + BLOCK_SIZE: tl.constexpr, +): + """ + Phase 1 for V: Compute partial absmax (no RoPE applied). + + Grid: (B, H, num_chunks) + + Uses linearized iteration over chunk_size * D elements. + """ + pid_b = tl.program_id(axis=0) + pid_h = tl.program_id(axis=1) + pid_chunk = tl.program_id(axis=2) + + # Compute the S range for this chunk + s_start = pid_chunk * chunk_size + s_end = tl.minimum(s_start + chunk_size, S) + chunk_elements = (s_end - s_start) * D + + # Base pointers for input [B, S, H, D] + in_base_b = pid_b * stride_in_b + in_base_h = pid_h * stride_in_h + + # Initialize max accumulator + v_max = 0.0 + + # Linearized iteration over chunk_size * D elements + for block_start in range(0, chunk_elements, BLOCK_SIZE): + offs = block_start + tl.arange(0, BLOCK_SIZE) + mask = offs < chunk_elements + + # Convert linear offset to (s, d) coordinates + local_s = offs // D + d_idx = offs % D + s_idx = s_start + local_s + + # Input offset [B, S, H, D] + in_offset = in_base_b + s_idx * stride_in_s + in_base_h + d_idx * stride_in_d + + v_val = tl.load(v_ptr + in_offset, mask=mask, other=0.0).to(tl.float32) + v_max = tl.maximum(v_max, tl.max(tl.abs(v_val))) + + # Store partial max + chunk_idx = pid_b * (H * num_chunks) + pid_h * num_chunks + pid_chunk + tl.store(partial_max_ptr + chunk_idx, v_max) + + +@triton.jit +def single_reduce_kernel( + partial_max_ptr, # [B * H * num_chunks] + scale_ptr, + descale_ptr, + H, + num_chunks, +): + """ + Reduce partial maxes and compute scale/descale for a single tensor. + + Grid: (B, H) + """ + pid_b = tl.program_id(axis=0) + pid_h = tl.program_id(axis=1) + + # Reduce across chunks for this (batch, head) + x_max = 0.0 + + base_idx = (pid_b * H + pid_h) * num_chunks + for c in range(num_chunks): + x_max = tl.maximum(x_max, tl.load(partial_max_ptr + base_idx + c)) + + # Compute scale and descale + # FP8 E4M3 max value is 448.0 + FP8_MAX = 448.0 + eps = 1e-12 + scale_idx = pid_b * H + pid_h + + tl.store(scale_ptr + scale_idx, tl.where(x_max > eps, FP8_MAX / x_max, 1.0)) + tl.store(descale_ptr + scale_idx, tl.where(x_max > eps, x_max / FP8_MAX, 1.0)) + + +@triton.jit +def group_reduce_kernel( + partial_max_ptr, # [B * H_q * num_chunks] + scale_ptr, # [B, H_kv] + descale_ptr, # [B, H_kv] + H_q, + H_kv, + groups, # H_q // H_kv + num_chunks, +): + """ + Reduce partial maxes across head groups for GQA Q tensor. + + For each KV group, reduces the max across all Q heads in that group + and all chunks, producing one scale per (batch, kv_head). + + Grid: (B, H_kv) + """ + pid_b = tl.program_id(axis=0) + pid_hkv = tl.program_id(axis=1) + + x_max = 0.0 + + for g in range(groups): + h_q = pid_hkv * groups + g + base_idx = (pid_b * H_q + h_q) * num_chunks + for c in range(num_chunks): + x_max = tl.maximum(x_max, tl.load(partial_max_ptr + base_idx + c)) + + FP8_MAX = 448.0 + eps = 1e-12 + scale_idx = pid_b * H_kv + pid_hkv + + tl.store(scale_ptr + scale_idx, tl.where(x_max > eps, FP8_MAX / x_max, 1.0)) + tl.store(descale_ptr + scale_idx, tl.where(x_max > eps, x_max / FP8_MAX, 1.0)) + + +@triton.autotune( + configs=[ + triton.Config({"BLOCK_SIZE": 512}, num_warps=4), + triton.Config({"BLOCK_SIZE": 1024}, num_warps=4), + triton.Config({"BLOCK_SIZE": 2048}, num_warps=8), + triton.Config({"BLOCK_SIZE": 4096}, num_warps=8), + ], + key=["chunk_size", "D"], +) +@triton.jit +def rope_single_phase2_kernel( + # Intermediate tensor [B, H, S, D] - already RoPE'd + x_rope_ptr, + # Output tensor [B, H, S, D] - FP8 quantized + x_out_ptr, + # Precomputed scale [B, H_scale] + scale_ptr, + # Strides (for [B, H, S, D] layout) - same for intermediate and output + stride_b, + stride_h, + stride_s, + stride_d, + # Dimensions + S, + D, + H, + chunk_size, + # Scale indexing for GQA: scale has H_scale entries per batch, + # and each group of `groups` heads shares one scale. + # For non-GQA: H_scale = H, groups = 1. + H_scale, + groups, + # Block size + BLOCK_SIZE: tl.constexpr, +): + """ + Phase 2 for a single tensor (Q or K): Quantize pre-computed RoPE'd values to FP8. + + Grid: (B, H, num_chunks) + """ + pid_b = tl.program_id(axis=0) + pid_h = tl.program_id(axis=1) + pid_chunk = tl.program_id(axis=2) + + # Load scale for this head (or head group for GQA) + scale = tl.load(scale_ptr + pid_b * H_scale + pid_h // groups) + + # Compute the S range for this chunk + s_start = pid_chunk * chunk_size + s_end = tl.minimum(s_start + chunk_size, S) + chunk_elements = (s_end - s_start) * D + + # Base pointer + base_offset = pid_b * stride_b + pid_h * stride_h + + # Linearized iteration over chunk_size * D elements + for block_start in range(0, chunk_elements, BLOCK_SIZE): + offs = block_start + tl.arange(0, BLOCK_SIZE) + mask = offs < chunk_elements + + # Convert linear offset to (s, d) coordinates + local_s = offs // D + d_idx = offs % D + s_idx = s_start + local_s + + ptr_offset = base_offset + s_idx * stride_s + d_idx * stride_d + + # Load pre-computed RoPE'd value from intermediate buffer + x_val = tl.load(x_rope_ptr + ptr_offset, mask=mask, other=0.0).to(tl.float32) + + # Quantize to FP8 + x_fp8 = (x_val * scale).to(tl.float8e4nv) + + # Store to output + tl.store(x_out_ptr + ptr_offset, x_fp8, mask=mask) + + +@triton.autotune( + configs=[ + triton.Config({"BLOCK_SIZE": 512}, num_warps=4), + triton.Config({"BLOCK_SIZE": 1024}, num_warps=4), + triton.Config({"BLOCK_SIZE": 2048}, num_warps=8), + triton.Config({"BLOCK_SIZE": 4096}, num_warps=8), + ], + key=["chunk_size", "D"], +) +@triton.jit +def v_phase2_kernel( + # Original V tensor [B, S, H, D] - needs transpose only + v_ptr, + # Output tensor [B, H, S, D] - FP8 quantized + v_out_ptr, + # Precomputed scale [B, H] + scale_ptr, + # V input strides (for [B, S, H, D] layout) + stride_v_in_b, + stride_v_in_s, + stride_v_in_h, + stride_v_in_d, + # Output strides (for [B, H, S, D] layout) + stride_out_b, + stride_out_h, + stride_out_s, + stride_out_d, + # Dimensions + S, + D, + H, + chunk_size, + # Block size + BLOCK_SIZE: tl.constexpr, +): + """ + Phase 2 for V: Transpose from [B,S,H,D] to [B,H,S,D] and quantize to FP8. + + Grid: (B, H, num_chunks) + """ + pid_b = tl.program_id(axis=0) + pid_h = tl.program_id(axis=1) + pid_chunk = tl.program_id(axis=2) + + # Load scale for this head + scale = tl.load(scale_ptr + pid_b * H + pid_h) + + # Compute the S range for this chunk + s_start = pid_chunk * chunk_size + s_end = tl.minimum(s_start + chunk_size, S) + chunk_elements = (s_end - s_start) * D + + # Base pointers + v_in_base = pid_b * stride_v_in_b + pid_h * stride_v_in_h + out_base = pid_b * stride_out_b + pid_h * stride_out_h + + # Linearized iteration over chunk_size * D elements + for block_start in range(0, chunk_elements, BLOCK_SIZE): + offs = block_start + tl.arange(0, BLOCK_SIZE) + mask = offs < chunk_elements + + # Convert linear offset to (s, d) coordinates + local_s = offs // D + d_idx = offs % D + s_idx = s_start + local_s + + # V input offset [B, S, H, D] + v_in_offset = v_in_base + s_idx * stride_v_in_s + d_idx * stride_v_in_d + + # Output offset [B, H, S, D] + out_offset = out_base + s_idx * stride_out_s + d_idx * stride_out_d + + # Load V from original input (no RoPE, just transpose) + v_val = tl.load(v_ptr + v_in_offset, mask=mask, other=0.0).to(tl.float32) + + # Quantize to FP8 + v_fp8 = (v_val * scale).to(tl.float8e4nv) + + # Store to output + tl.store(v_out_ptr + out_offset, v_fp8, mask=mask) + + +def triton_fp8_rope_sdpa_quantize( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + cos: torch.Tensor, + sin: torch.Tensor, + num_chunks: Optional[int] = None, + rope_interleaved: bool = False, +) -> Tuple[ + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, +]: + """ + Separated RoPE + FP8 quantization for Q, K, V tensors. + + Applies RoPE to Q and K, then quantizes all tensors to FP8 with per-head scaling. + Also performs layout transformation from [B, S, H, D] to [B, H, S, D]. + Each of Q, K, V is processed with independent kernel launches. + + Supports GQA where Q has more heads than K/V (H_q = groups * H_kv). + For GQA, Q is quantized with per-KV-group scaling so that q_descale + has shape [B, H_kv] as required by FA3. + + Args: + q: Query tensor of shape [B, S, H_q, D] in bf16/fp16 + k: Key tensor of shape [B, S, H_kv, D] in bf16/fp16 + v: Value tensor of shape [B, S, H_kv, D] in bf16/fp16 + cos: Cosine frequencies for RoPE, shape [S, D] + sin: Sine frequencies for RoPE, shape [S, D] + num_chunks: Number of chunks to split S dimension into. + If None, automatically selects based on GPU SM count. + + Returns: + q_fp8: Quantized query with RoPE, shape [B, H_q, S, D] in fp8 + k_fp8: Quantized key with RoPE, shape [B, H_kv, S, D] in fp8 + v_fp8: Quantized value, shape [B, H_kv, S, D] in fp8 + q_descale: Query descale factors, shape [B, H_kv] in fp32 + k_descale: Key descale factors, shape [B, H_kv] in fp32 + v_descale: Value descale factors, shape [B, H_kv] in fp32 + """ + assert q.dim() == 4, f"Expected 4D tensor [B, S, H, D], got {q.dim()}D" + assert k.dim() == 4, f"Expected 4D tensor [B, S, H, D], got {k.dim()}D" + assert v.dim() == 4, f"Expected 4D tensor [B, S, H, D], got {v.dim()}D" + assert k.shape == v.shape, ( + f"K and V must have the same shape, got {k.shape} vs {v.shape}" + ) + assert q.shape[0] == k.shape[0], ( + f"Batch size mismatch: {q.shape[0]} vs {k.shape[0]}" + ) + assert q.shape[1] == k.shape[1], ( + f"Sequence length mismatch: {q.shape[1]} vs {k.shape[1]}" + ) + assert q.shape[3] == k.shape[3], f"Head dim mismatch: {q.shape[3]} vs {k.shape[3]}" + assert q.shape[2] % k.shape[2] == 0, ( + f"Q heads ({q.shape[2]}) must be a multiple of K heads ({k.shape[2]})" + ) + assert cos.dim() == 2, f"Expected 2D cos tensor [S, D], got {cos.dim()}D" + assert sin.dim() == 2, f"Expected 2D sin tensor [S, D], got {sin.dim()}D" + + B, S, H_q, D = q.shape + H_kv = k.shape[2] + groups = H_q // H_kv + + assert D % 2 == 0, f"Head dimension D must be even for RoPE, got D={D}" + assert cos.shape == (S, D), f"Expected cos shape [{S}, {D}], got {cos.shape}" + assert sin.shape == (S, D), f"Expected sin shape [{S}, {D}], got {sin.shape}" + + D_HALF = D // 2 + + # Make tensors contiguous if needed + q = q.contiguous() + k = k.contiguous() + v = v.contiguous() + cos = cos.contiguous() + sin = sin.contiguous() + + # Compute number of chunks + if num_chunks is None: + num_chunks = _compute_num_chunks(q, S) + chunk_size = (S + num_chunks - 1) // num_chunks + + # Allocate output tensors in [B, H, S, D] layout for SDPA + q_fp8 = torch.empty(B, H_q, S, D, dtype=torch.float8_e4m3fn, device=q.device) + k_fp8 = torch.empty(B, H_kv, S, D, dtype=torch.float8_e4m3fn, device=q.device) + v_fp8 = torch.empty(B, H_kv, S, D, dtype=torch.float8_e4m3fn, device=q.device) + + # Allocate intermediate buffers for RoPE'd Q, K in [B, H, S, D] layout + q_rope_intermediate = torch.empty(B, H_q, S, D, dtype=q.dtype, device=q.device) + k_rope_intermediate = torch.empty(B, H_kv, S, D, dtype=k.dtype, device=q.device) + + # Allocate partial max buffers (one per tensor) + q_partial_max = torch.empty( + B * H_q * num_chunks, dtype=torch.float32, device=q.device + ) + k_partial_max = torch.empty( + B * H_kv * num_chunks, dtype=torch.float32, device=q.device + ) + v_partial_max = torch.empty( + B * H_kv * num_chunks, dtype=torch.float32, device=q.device + ) + + # Allocate scale/descale tensors. + # For GQA, Q scale/descale are [B, H_kv] (per KV group). + # K and V are always [B, H_kv] (per head). + q_scale = torch.empty(B, H_kv, dtype=torch.float32, device=q.device) + k_scale = torch.empty(B, H_kv, dtype=torch.float32, device=q.device) + v_scale = torch.empty(B, H_kv, dtype=torch.float32, device=q.device) + q_descale = torch.empty(B, H_kv, dtype=torch.float32, device=q.device) + k_descale = torch.empty(B, H_kv, dtype=torch.float32, device=q.device) + v_descale = torch.empty(B, H_kv, dtype=torch.float32, device=q.device) + + q_grid_chunked = (B, H_q, num_chunks) + kv_grid_chunked = (B, H_kv, num_chunks) + + # ---- Phase 1: RoPE + max for Q ---- + rope_single_phase1_kernel[q_grid_chunked]( + q, + cos, + sin, + q_rope_intermediate, + q_partial_max, + # Input strides [B, S, H_q, D] + q.stride(0), + q.stride(1), + q.stride(2), + q.stride(3), + # Output strides [B, H_q, S, D] + q_rope_intermediate.stride(0), + q_rope_intermediate.stride(1), + q_rope_intermediate.stride(2), + q_rope_intermediate.stride(3), + S, + D, + D_HALF, + H_q, + chunk_size, + num_chunks, + ROPE_INTERLEAVED=rope_interleaved, + ) + + # ---- Phase 1: RoPE + max for K ---- + rope_single_phase1_kernel[kv_grid_chunked]( + k, + cos, + sin, + k_rope_intermediate, + k_partial_max, + # Input strides [B, S, H_kv, D] + k.stride(0), + k.stride(1), + k.stride(2), + k.stride(3), + # Output strides [B, H_kv, S, D] + k_rope_intermediate.stride(0), + k_rope_intermediate.stride(1), + k_rope_intermediate.stride(2), + k_rope_intermediate.stride(3), + S, + D, + D_HALF, + H_kv, + chunk_size, + num_chunks, + ROPE_INTERLEAVED=rope_interleaved, + ) + + # ---- Phase 1: Max for V (no RoPE) ---- + v_phase1_kernel[kv_grid_chunked]( + v, + v_partial_max, + # Input strides [B, S, H_kv, D] + v.stride(0), + v.stride(1), + v.stride(2), + v.stride(3), + S, + D, + H_kv, + chunk_size, + num_chunks, + ) + + # ---- Reduce ---- + # Q: group reduce across `groups` Q heads per KV head + group_reduce_kernel[(B, H_kv)]( + q_partial_max, q_scale, q_descale, H_q, H_kv, groups, num_chunks + ) + # K, V: per-head reduce + single_reduce_kernel[(B, H_kv)](k_partial_max, k_scale, k_descale, H_kv, num_chunks) + single_reduce_kernel[(B, H_kv)](v_partial_max, v_scale, v_descale, H_kv, num_chunks) + + # ---- Phase 2: Quantize Q from intermediate ---- + # Q scale is [B, H_kv]; each group of `groups` Q heads shares one scale. + rope_single_phase2_kernel[q_grid_chunked]( + q_rope_intermediate, + q_fp8, + q_scale, + # Strides [B, H_q, S, D] + q_fp8.stride(0), + q_fp8.stride(1), + q_fp8.stride(2), + q_fp8.stride(3), + S, + D, + H_q, + chunk_size, + H_kv, + groups, + ) + + # ---- Phase 2: Quantize K from intermediate ---- + # K scale is [B, H_kv]; groups=1 (per-head). + rope_single_phase2_kernel[kv_grid_chunked]( + k_rope_intermediate, + k_fp8, + k_scale, + # Strides [B, H_kv, S, D] + k_fp8.stride(0), + k_fp8.stride(1), + k_fp8.stride(2), + k_fp8.stride(3), + S, + D, + H_kv, + chunk_size, + H_kv, + 1, + ) + + # ---- Phase 2: Transpose + quantize V ---- + v_phase2_kernel[kv_grid_chunked]( + v, + v_fp8, + v_scale, + # V input strides [B, S, H_kv, D] + v.stride(0), + v.stride(1), + v.stride(2), + v.stride(3), + # Output strides [B, H_kv, S, D] + v_fp8.stride(0), + v_fp8.stride(1), + v_fp8.stride(2), + v_fp8.stride(3), + S, + D, + H_kv, + chunk_size, + ) + + return q_fp8, k_fp8, v_fp8, q_descale, k_descale, v_descale diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ecddc88b5fe964969113ce7016cc2371eaa3a2e3 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cda37ffdfe3e807ef360b02cf7fc1ac77bf97569 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__pycache__/attention.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__pycache__/attention.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..754d673d3953128b95432f6d02ca66cab6bfe962 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__pycache__/attention.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__pycache__/custom_ops.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__pycache__/custom_ops.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..380e5c41e24983ca09a7fcc7633013a3fe41597b Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__pycache__/custom_ops.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__pycache__/fusion_utils.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__pycache__/fusion_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9fabe634a142b8974d3747576b7fdade184bb27 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__pycache__/fusion_utils.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__pycache__/setup.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__pycache__/setup.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f7a4488cb98de431c272ce0f7e31ecf21619f7e Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__pycache__/setup.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__pycache__/wrapper.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__pycache__/wrapper.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b7dcb7ea34308e62e76ef3383890048744b00aa1 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__pycache__/wrapper.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/attention.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/attention.py new file mode 100644 index 0000000000000000000000000000000000000000..248668639a0ceb2d4fa2f389ae7bf702624570f0 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/attention.py @@ -0,0 +1,135 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +""" +Shared FP8 scaled dot-product attention implementation. + +Backend-specific modules (``fp8_fa3/attention.py``, etc.) provide thin +named wrappers around these functions via ``functools.partial``. +""" + +from typing import Optional + +import torch + +from torchao.utils import torch_version_at_least + +_TORCH_VERSION_AT_LEAST_2_11 = torch_version_at_least("2.11.0") + +if _TORCH_VERSION_AT_LEAST_2_11: + from torch.nn.attention import SDPBackend, sdpa_kernel + from torch.nn.attention.experimental._scaled_dot_product_attention_quantized import ( + _scaled_dot_product_attention_quantized, + ) + +from torchao.prototype.attention.quantization import ( + _fp8_rope_sdpa_quantize, + _fp8_sdpa_quantize, +) + + +def _fp8_sdpa( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + attn_mask: Optional[torch.Tensor] = None, + dropout_p: float = 0.0, + is_causal: bool = False, + scale: Optional[float] = None, + enable_gqa: bool = False, + *, + backend_name: str = "FP8", +) -> torch.Tensor: + """FP8 SDPA shared by all backends. + + The correct flash attention implementation (e.g. FA3) must be + activated before calling this function. The high-level + ``apply_low_precision_attention`` API handles this automatically. + + Input/output layout: [B, H, S, D]. + """ + if not _TORCH_VERSION_AT_LEAST_2_11: + raise RuntimeError("Low-precision attention requires PyTorch 2.11+.") + if attn_mask is not None: + raise ValueError(f"attn_mask not supported for FP8 {backend_name}") + if dropout_p != 0.0: + raise ValueError( + f"dropout_p must be 0.0 for FP8 {backend_name}, got {dropout_p}" + ) + + input_dtype = query.dtype + + q_fp8, k_fp8, v_fp8, descale_q, descale_k, descale_v = _fp8_sdpa_quantize( + query, key, value + ) + + with sdpa_kernel(SDPBackend.FLASH_ATTENTION): + out = _scaled_dot_product_attention_quantized( + q_fp8, + k_fp8, + v_fp8, + is_causal=is_causal, + scale=scale, + q_descale=descale_q, + k_descale=descale_k, + v_descale=descale_v, + ) + + return out.to(input_dtype) + + +def _fp8_rope_sdpa( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + cos: torch.Tensor, + sin: torch.Tensor, + attn_mask: Optional[torch.Tensor] = None, + dropout_p: float = 0.0, + is_causal: bool = False, + scale: Optional[float] = None, + enable_gqa: bool = False, + rope_interleaved: bool = False, + *, + backend_name: str = "FP8", +) -> torch.Tensor: + """Fused RoPE + FP8 SDPA shared by all backends. + + Input layout: [B, S, H, D] (pre-transpose). The fused quantization + kernel handles the transpose to [B, H, S, D] internally. + Output layout: [B, H, S, D]. + """ + if not _TORCH_VERSION_AT_LEAST_2_11: + raise RuntimeError("Low-precision attention requires PyTorch 2.11+.") + if attn_mask is not None: + raise ValueError(f"attn_mask not supported for FP8 {backend_name}") + if dropout_p != 0.0: + raise ValueError( + f"dropout_p must be 0.0 for FP8 {backend_name}, got {dropout_p}" + ) + + input_dtype = query.dtype + + cos = cos.to(query.device) + sin = sin.to(query.device) + + q_fp8, k_fp8, v_fp8, descale_q, descale_k, descale_v = _fp8_rope_sdpa_quantize( + query, key, value, cos, sin, rope_interleaved=rope_interleaved + ) + + with sdpa_kernel(SDPBackend.FLASH_ATTENTION): + out = _scaled_dot_product_attention_quantized( + q_fp8, + k_fp8, + v_fp8, + is_causal=is_causal, + scale=scale, + q_descale=descale_q, + k_descale=descale_k, + v_descale=descale_v, + ) + + return out.to(input_dtype) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/custom_ops.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/custom_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..509683e63ce055731382d2e9adad85c7b39e428b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/custom_ops.py @@ -0,0 +1,112 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +""" +Shared custom op registration and compile helpers for FP8 attention backends. + +Custom ops are needed because our FP8 SDPA functions call Triton kernels +that are not traceable by torch.compile. Registering them as custom_ops +tells the compiler to treat them as opaque nodes with known shapes/dtypes. +""" + +from typing import Callable, NamedTuple + +import torch + + +class RegisteredOps(NamedTuple): + rope_sdpa_op: object + fp8_sdpa_op: object + + +def register_fp8_attention_ops( + backend_name: str, + rope_sdpa_fn: Callable, + sdpa_fn: Callable, +) -> RegisteredOps: + """Register the RoPE+SDPA and plain SDPA custom ops for a backend.""" + backend = backend_name.lower() + + rope_op_name = f"torchao::fp8_{backend}_rope_sdpa" + + @torch.library.custom_op(rope_op_name, mutates_args=()) + def _rope_sdpa_custom_op( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + cos: torch.Tensor, + sin: torch.Tensor, + is_causal: bool = False, + scale: float = 0.0, + enable_gqa: bool = False, + rope_interleaved: bool = False, + ) -> torch.Tensor: + actual_scale = scale if scale != 0.0 else None + return rope_sdpa_fn( + q, + k, + v, + cos, + sin, + is_causal=is_causal, + scale=actual_scale, + enable_gqa=enable_gqa, + rope_interleaved=rope_interleaved, + ) + + @_rope_sdpa_custom_op.register_fake + def _rope_sdpa_fake( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + cos: torch.Tensor, + sin: torch.Tensor, + is_causal: bool = False, + scale: float = 0.0, + enable_gqa: bool = False, + rope_interleaved: bool = False, + ) -> torch.Tensor: + B, S, H, D = q.shape + return torch.empty(B, H, S, D, dtype=q.dtype, device=q.device) + + sdpa_op_name = f"torchao::fp8_{backend}_sdpa" + + @torch.library.custom_op(sdpa_op_name, mutates_args=()) + def _sdpa_custom_op( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + is_causal: bool = False, + scale: float = 0.0, + enable_gqa: bool = False, + ) -> torch.Tensor: + actual_scale = scale if scale != 0.0 else None + return sdpa_fn( + q, + k, + v, + is_causal=is_causal, + scale=actual_scale, + enable_gqa=enable_gqa, + ) + + @_sdpa_custom_op.register_fake + def _sdpa_fake( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + is_causal: bool = False, + scale: float = 0.0, + enable_gqa: bool = False, + ) -> torch.Tensor: + return torch.empty(q.shape, dtype=q.dtype, device=q.device) + + rope_sdpa_op = getattr( + getattr(torch.ops, "torchao"), f"fp8_{backend}_rope_sdpa" + ).default + fp8_sdpa_op = getattr(getattr(torch.ops, "torchao"), f"fp8_{backend}_sdpa").default + + return RegisteredOps(rope_sdpa_op=rope_sdpa_op, fp8_sdpa_op=fp8_sdpa_op) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/fusion_utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/fusion_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..66189e0ed295ace5c062ab3a7638f020b1005386 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/fusion_utils.py @@ -0,0 +1,908 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +""" +Shared FX graph pattern detection and fusion utilities for low-precision attention. +""" + +import logging +import operator +from dataclasses import dataclass +from typing import Optional, Tuple + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch.fx import Graph, Node + +logger = logging.getLogger(__name__) + + +@dataclass +class RoPEMatch: + """Result of detecting a RoPE pattern on a tensor.""" + + pre_rope_input: Node # tensor before RoPE: "x" in "x * cos + rotate_half(x) * sin" + cos_node: Node # cosine frequencies, traced back to [S, D] source + sin_node: Node # sine frequencies, traced back to [S, D] source + rope_interleaved: bool # True = FLUX interleaved, False = NeoX half-split + + +# FX Node Utilities + + +def _is_op(node: Node, *targets) -> bool: + """Check if an FX node matches one of the given targets.""" + if node.op in ("call_function", "call_method"): + return node.target in targets + return False + + +def _get_fake_tensor(node: Node) -> Optional[torch.Tensor]: + """Get the FakeTensor metadata from a node (pre-grad or post-grad).""" + for key in ("val", "example_value"): + if key in node.meta: + val = node.meta[key] + if isinstance(val, torch.Tensor): + return val + return None + + +def _get_node_shape(node: Node) -> Optional[Tuple[int, ...]]: + fake = _get_fake_tensor(node) + if fake is not None: + return tuple(fake.shape) + return None + + +def _reshape_cos_sin_to_2d( + graph: Graph, + cos_node: Node, + sin_node: Node, + insert_before: Node, +) -> Optional[Tuple[Node, Node]]: + """Reshape cos/sin nodes to 2D [S, D] if they have leading size-1 dims. + + HuggingFace models produce cos/sin with shape [B, S, D] or [1, 1, S, D]. + """ + cos_shape = _get_node_shape(cos_node) + sin_shape = _get_node_shape(sin_node) + + if cos_shape is None or sin_shape is None: + return cos_node, sin_node + + if len(cos_shape) == 2 and len(sin_shape) == 2: + return cos_node, sin_node + + for name, shape in [("cos", cos_shape), ("sin", sin_shape)]: + if len(shape) < 2: + logger.debug("RoPE %s has fewer than 2 dims: shape=%s", name, shape) + return None + for dim in shape[:-2]: + if dim != 1: + logger.debug( + "RoPE %s has non-unit leading dim: shape=%s", + name, + shape, + ) + return None + + s, d = cos_shape[-2], cos_shape[-1] + with graph.inserting_before(insert_before): + cos_2d = graph.call_function( + torch.ops.aten.view.default, + args=(cos_node, [s, d]), + ) + sin_2d = graph.call_function( + torch.ops.aten.view.default, + args=(sin_node, [s, d]), + ) + return cos_2d, sin_2d + + +def _trace_through_views(node: Node) -> Node: + """Trace backward through view-like ops (unsqueeze, expand, clone, to.dtype, etc.).""" + current = node + while isinstance(current, Node): + if current.op == "call_function" and current.target in ( + torch.ops.aten.unsqueeze.default, + torch.ops.aten.clone.default, + torch.ops.aten.contiguous.default, + torch.ops.aten.expand.default, + torch.ops.aten.to.dtype, + torch.ops.aten._to_copy.default, + ): + current = current.args[0] + elif current.op == "call_method" and current.target in ( + "unsqueeze", + "clone", + "contiguous", + "expand", + "to", + "float", + "half", + "bfloat16", + ): + current = current.args[0] + elif ( + current.op == "call_function" + and current.target is operator.getitem + and len(current.args) >= 2 + and isinstance(current.args[1], tuple) + and all(i is None or i == slice(None) for i in current.args[1]) + ): + current = current.args[0] + else: + break + return current + + +# Transpose Detection + + +def _unwrap_transpose(node: Node) -> Optional[Node]: + """If node is transpose(1,2) or permute([0,2,1,3]), return its input. + + Also looks through contiguous()/clone() wrappers. + """ + if not isinstance(node, Node): + return None + + current = node + while isinstance(current, Node) and _is_op( + current, + torch.ops.aten.contiguous.default, + torch.ops.aten.clone.default, + "contiguous", + "clone", + ): + current = current.args[0] + + if not isinstance(current, Node): + return None + + # aten.transpose.int(tensor, 1, 2) + if _is_op(current, torch.ops.aten.transpose.int): + if len(current.args) >= 3: + dim0, dim1 = current.args[1], current.args[2] + if (dim0 == 1 and dim1 == 2) or (dim0 == 2 and dim1 == 1): + return current.args[0] + + # aten.permute.default(tensor, [0, 2, 1, 3]) + if _is_op(current, torch.ops.aten.permute.default): + if len(current.args) >= 2: + perm = current.args[1] + if list(perm) == [0, 2, 1, 3]: + return current.args[0] + + # call_method transpose(1, 2) + if _is_op(current, "transpose"): + if len(current.args) >= 3: + dim0, dim1 = current.args[1], current.args[2] + if (dim0 == 1 and dim1 == 2) or (dim0 == 2 and dim1 == 1): + return current.args[0] + + # call_method permute(0, 2, 1, 3) + if _is_op(current, "permute"): + if len(current.args) >= 5: + perm = list(current.args[1:5]) + if perm == [0, 2, 1, 3]: + return current.args[0] + elif len(current.args) >= 2 and isinstance(current.args[1], (list, tuple)): + perm = current.args[1] + if list(perm) == [0, 2, 1, 3]: + return current.args[0] + + return None + + +def _unwrap_repeat_kv(node: Node) -> Optional[Node]: + """Unwrap HuggingFace's repeat_kv (GQA head repetition) pattern. + + Pattern: reshape <- expand <- getitem(unsqueeze). + Returns the pre-repetition tensor, or None. + """ + if not isinstance(node, Node): + return None + + if not _is_op( + node, + torch.ops.aten.reshape.default, + torch.ops.aten.view.default, + "reshape", + "view", + ): + return None + + inner = node.args[0] if node.args else None + if not isinstance(inner, Node): + return None + + if not _is_op(inner, torch.ops.aten.expand.default, "expand"): + return None + + inner2 = inner.args[0] if inner.args else None + if not isinstance(inner2, Node): + return None + + if _is_op(inner2, torch.ops.aten.unsqueeze.default, "unsqueeze"): + return inner2.args[0] if inner2.args else None + + if inner2.op == "call_function" and inner2.target is operator.getitem: + if len(inner2.args) >= 2 and isinstance(inner2.args[1], tuple): + if any(i is None for i in inner2.args[1]): + return inner2.args[0] if inner2.args else None + + return None + + +# SDPA Detection and Parameter Extraction + + +def _is_fp8_sdpa_node(node: Node, fp8_sdpa_op) -> bool: + """Check if an FX node is our FP8 SDPA custom op.""" + return node.op == "call_function" and node.target is fp8_sdpa_op + + +def _is_sdpa_node(node: Node) -> bool: + """Check if an FX node is ``aten.scaled_dot_product_attention``.""" + return _is_op( + node, + torch.ops.aten.scaled_dot_product_attention.default, + torch._C._nn.scaled_dot_product_attention, + ) + + +def _sdpa_is_fusible(node: Node, strip_causal_mask: bool = False) -> Tuple[bool, bool]: + """Check if an aten SDPA node is compatible with our FP8 fused kernel. + + Returns (is_fusible, needs_mask_strip). + """ + args = node.args + kwargs = node.kwargs + + attn_mask = args[3] if len(args) > 3 else kwargs.get("attn_mask", None) + is_causal = args[5] if len(args) > 5 else kwargs.get("is_causal", False) + + needs_mask_strip = False + if attn_mask is not None: + if not is_causal and strip_causal_mask and isinstance(attn_mask, Node): + needs_mask_strip = True + else: + return False, False + + dropout_p = args[4] if len(args) > 4 else kwargs.get("dropout_p", 0.0) + if dropout_p != 0.0: + return False, False + + return True, needs_mask_strip + + +def _strip_causal_mask(node: Node) -> None: + """Strip a materialized causal mask from an aten SDPA node.""" + args = list(node.args) + kwargs = dict(node.kwargs) + + if len(args) > 3: + args[3] = None + elif "attn_mask" in kwargs: + kwargs["attn_mask"] = None + + if len(args) > 5: + args[5] = True + elif "is_causal" in kwargs: + kwargs["is_causal"] = True + else: + kwargs["is_causal"] = True + + node.args = tuple(args) + node.kwargs = kwargs + + logger.info("Stripped causal mask from SDPA node: %s", node.name) + + +def _is_lower_triangular_bool_mask(mask: torch.Tensor) -> bool: + """Check if a tensor is a bool, square lower-triangular (causal) mask.""" + if mask.dtype != torch.bool or mask.ndim < 2: + return False + q_len, kv_len = mask.shape[-2], mask.shape[-1] + if q_len != kv_len: + return False + ref = torch.tril(torch.ones(q_len, kv_len, dtype=torch.bool, device=mask.device)) + return torch.equal(mask.broadcast_to(mask.shape), ref.expand_as(mask)) + + +def detect_causal_mask( + model: nn.Module, + sample_input_ids=None, + flash_impl_name: str | None = None, +) -> bool: + """Run one forward pass to detect whether the model uses causal masks. + + Returns True when every SDPA call used causal attention (either via + a materialized lower-triangular bool mask, or via is_causal=True). + """ + from torch.nn.attention import ( + activate_flash_attention_impl, + restore_flash_attention_impl, + ) + + try: + device = next(model.parameters()).device + except StopIteration: + return False + + if sample_input_ids is None: + vocab_size = getattr(getattr(model, "config", None), "vocab_size", None) + if vocab_size is None: + return False + sample_input_ids = torch.randint(0, vocab_size, (1, 16), device=device) + + all_causal: list[bool] = [] + saw_any_sdpa = False + + original_sdpa = F.scaled_dot_product_attention + + def _hook(*args, **kwargs): + nonlocal saw_any_sdpa + saw_any_sdpa = True + attn_mask = args[3] if len(args) > 3 else kwargs.get("attn_mask", None) + is_causal = kwargs.get("is_causal", False) if len(args) <= 5 else args[5] + + if attn_mask is not None and not is_causal: + all_causal.append(_is_lower_triangular_bool_mask(attn_mask)) + elif attn_mask is None and is_causal: + all_causal.append(True) + + return original_sdpa(*args, **kwargs) + + F.scaled_dot_product_attention = _hook + if flash_impl_name is not None: + activate_flash_attention_impl(flash_impl_name) + try: + with torch.no_grad(): + model(sample_input_ids) + except Exception: + logger.debug("detect_causal_mask: forward pass failed", exc_info=True) + return False + finally: + F.scaled_dot_product_attention = original_sdpa + if flash_impl_name is not None: + restore_flash_attention_impl() + + if not saw_any_sdpa: + return False + + return all(all_causal) + + +def _get_fp8_sdpa_params(node: Node) -> Tuple[bool, float, bool]: + """Extract is_causal, scale, and enable_gqa from an FP8 SDPA custom op node. + + Custom op signature: (q, k, v, is_causal=False, scale=0.0, enable_gqa=False) + Scale uses 0.0 as sentinel for "default" (1/sqrt(D)). + """ + args = node.args + kwargs = node.kwargs + + is_causal = args[3] if len(args) > 3 else kwargs.get("is_causal", False) + scale = args[4] if len(args) > 4 else kwargs.get("scale", 0.0) + enable_gqa = args[5] if len(args) > 5 else kwargs.get("enable_gqa", False) + + return is_causal, scale, enable_gqa + + +def _get_fp8_sdpa_qkv(node: Node) -> Optional[Tuple[Node, Node, Node]]: + """Extract Q, K, V input nodes from an FP8 SDPA custom op node.""" + args = node.args + kwargs = node.kwargs + + q = args[0] if len(args) > 0 else kwargs.get("q", None) + k = args[1] if len(args) > 1 else kwargs.get("k", None) + v = args[2] if len(args) > 2 else kwargs.get("v", None) + + if not all(isinstance(n, Node) for n in (q, k, v)): + return None + + return q, k, v + + +# NeoX/LLaMA RoPE Pattern Detection +# +# NeoX/LLaMA RoPE: +# rotate_half(x) = cat(-x[..., D//2:], x[..., :D//2], dim=-1) +# apply_rope(x, cos, sin) = x * cos + rotate_half(x) * sin + + +def _detect_rotate_half(cat_node: Node) -> Optional[Node]: + """Detect rotate_half(x) = cat(-x[..., D//2:], x[..., :D//2], dim=-1). + + Returns the source tensor x, or None. + """ + if not _is_op(cat_node, torch.ops.aten.cat.default, torch.cat): + return None + + if len(cat_node.args) < 1: + return None + + tensors_list = cat_node.args[0] + + if len(cat_node.args) >= 2: + cat_dim = cat_node.args[1] + else: + cat_dim = cat_node.kwargs.get("dim", 0) + + if cat_dim not in (-1, 3): + return None + + if not isinstance(tensors_list, (list, tuple)) or len(tensors_list) != 2: + return None + + neg_part = tensors_list[0] + pos_part = tensors_list[1] + + if not isinstance(neg_part, Node) or not isinstance(pos_part, Node): + return None + + if not _is_op(neg_part, torch.ops.aten.neg.default, operator.neg, torch.neg): + return None + + neg_input = neg_part.args[0] + if not isinstance(neg_input, Node): + return None + + return _match_rotate_half_slices(neg_input, pos_part) + + +def _match_rotate_half_slices(neg_input: Node, pos_part: Node) -> Optional[Node]: + """Match the slice patterns in rotate_half. Returns the source tensor x, or None.""" + # ATen slice pattern + if _is_op(neg_input, torch.ops.aten.slice.Tensor) and _is_op( + pos_part, torch.ops.aten.slice.Tensor + ): + slice_neg_source = neg_input.args[0] + slice_pos_source = pos_part.args[0] + + if slice_neg_source is not slice_pos_source: + return None + + slice_neg_dim = neg_input.args[1] if len(neg_input.args) > 1 else 0 + slice_pos_dim = pos_part.args[1] if len(pos_part.args) > 1 else 0 + + if slice_neg_dim not in (-1, 3) or slice_pos_dim not in (-1, 3): + return None + + pos_start = pos_part.args[2] if len(pos_part.args) > 2 else None + pos_end = pos_part.args[3] if len(pos_part.args) > 3 else None + neg_start = neg_input.args[2] if len(neg_input.args) > 2 else None + + if pos_start != 0: + return None + if neg_start is None or pos_end is None: + return None + if neg_start != pos_end: + return None + + return slice_neg_source + + # Dynamo getitem pattern + if _is_op(neg_input, operator.getitem) and _is_op(pos_part, operator.getitem): + slice_neg_source = neg_input.args[0] + slice_pos_source = pos_part.args[0] + + if slice_neg_source is not slice_pos_source: + return None + + neg_idx = neg_input.args[1] + pos_idx = pos_part.args[1] + + neg_slice = _extract_last_dim_slice(neg_idx) + pos_slice = _extract_last_dim_slice(pos_idx) + + if neg_slice is None or pos_slice is None: + return None + + if pos_slice.start not in (0, None): + return None + if pos_slice.stop is None: + return None + if neg_slice.start is None: + return None + if neg_slice.start != pos_slice.stop: + return None + + return slice_neg_source + + return None + + +def _extract_last_dim_slice(idx) -> Optional[slice]: + """Extract the slice on the last dimension from a getitem index.""" + if isinstance(idx, tuple): + if len(idx) >= 2 and idx[0] is Ellipsis and isinstance(idx[1], slice): + return idx[1] + if len(idx) >= 1 and isinstance(idx[-1], slice): + for i in range(len(idx) - 1): + if idx[i] is not Ellipsis and idx[i] != slice(None): + return None + return idx[-1] + elif isinstance(idx, slice): + return idx + return None + + +def _detect_interleaved_rotation(node: Node) -> Optional[Node]: + """Detect the FLUX-style interleaved rotation pattern. + + Pattern: x.reshape(..., -1, 2).unbind(-1) -> stack([-x_imag, x_real], dim=-1).flatten(3) + Returns the source tensor x, or None. + """ + if not _is_op(node, torch.ops.aten.flatten.using_ints, "flatten"): + return None + if len(node.args) < 1: + return None + + stack_node = node.args[0] + if not isinstance(stack_node, Node): + return None + + if not _is_op(stack_node, torch.ops.aten.stack.default, torch.stack): + return None + if len(stack_node.args) < 1: + return None + + tensors_list = stack_node.args[0] + if len(stack_node.args) >= 2: + stack_dim = stack_node.args[1] + else: + stack_dim = stack_node.kwargs.get("dim", 0) + if stack_dim != -1: + return None + + if not isinstance(tensors_list, (list, tuple)) or len(tensors_list) != 2: + return None + + neg_part = tensors_list[0] + pos_part = tensors_list[1] + if not isinstance(neg_part, Node) or not isinstance(pos_part, Node): + return None + + if not _is_op(neg_part, torch.ops.aten.neg.default, operator.neg, torch.neg): + return None + + x_imag = neg_part.args[0] + if not isinstance(x_imag, Node): + return None + + if not _is_op(pos_part, operator.getitem) or not _is_op(x_imag, operator.getitem): + return None + + real_source = pos_part.args[0] + imag_source = x_imag.args[0] + if real_source is not imag_source: + return None + if pos_part.args[1] != 0 or x_imag.args[1] != 1: + return None + + unbind_node = real_source + if not isinstance(unbind_node, Node): + return None + if not _is_op(unbind_node, torch.ops.aten.unbind.int, "unbind"): + return None + + if len(unbind_node.args) >= 2: + unbind_dim = unbind_node.args[1] + else: + unbind_dim = unbind_node.kwargs.get("dim", 0) + if unbind_dim != -1: + return None + + reshape_node = unbind_node.args[0] + if not isinstance(reshape_node, Node): + return None + if not _is_op( + reshape_node, + torch.ops.aten.reshape.default, + torch.ops.aten.view.default, + "reshape", + "view", + ): + return None + + source_x = reshape_node.args[0] + return source_x if isinstance(source_x, Node) else None + + +def _detect_rotation(node: Node) -> Optional[Tuple[Node, bool]]: + """Detect any supported rotation pattern. + + Returns (source_tensor, is_interleaved) or None. + """ + result = _detect_rotate_half(node) + if result is not None: + return result, False + + result = _detect_interleaved_rotation(node) + if result is not None: + return result, True + + return None + + +def _detect_neox_rope(node: Node) -> Optional[RoPEMatch]: + """Detect the NeoX/LLaMA RoPE pattern: add(mul(x, cos), mul(rotate_half(x), sin)).""" + if not _is_op(node, torch.ops.aten.add.Tensor, operator.add): + return None + if len(node.args) < 2: + return None + + left = node.args[0] + right = node.args[1] + if not isinstance(left, Node) or not isinstance(right, Node): + return None + + if not _is_op(left, torch.ops.aten.mul.Tensor, operator.mul): + return None + if not _is_op(right, torch.ops.aten.mul.Tensor, operator.mul): + return None + + def _try_match(x_mul: Node, rot_mul: Node) -> Optional[RoPEMatch]: + rot_a, rot_b = rot_mul.args[0], rot_mul.args[1] + + for rot_candidate, sin_candidate in [(rot_a, rot_b), (rot_b, rot_a)]: + if not isinstance(rot_candidate, Node): + continue + + rot_unwrapped = _trace_through_views(rot_candidate) + rotation_result = _detect_rotation(rot_unwrapped) + if rotation_result is None: + continue + x_from_rotate, is_interleaved = rotation_result + + x_a, x_b = x_mul.args[0], x_mul.args[1] + for x_candidate, cos_candidate in [(x_a, x_b), (x_b, x_a)]: + if not isinstance(x_candidate, Node): + continue + + x_traced = _trace_through_views(x_candidate) + if x_traced is not x_from_rotate: + continue + + cos_source = _trace_through_views(cos_candidate) + sin_source = _trace_through_views(sin_candidate) + + return RoPEMatch( + pre_rope_input=x_from_rotate, + cos_node=cos_source, + sin_node=sin_source, + rope_interleaved=is_interleaved, + ) + + return None + + # Try both orderings of the add (commutative). + result = _try_match(left, right) + if result is not None: + return result + return _try_match(right, left) + + +def _detect_rope(node: Node) -> Optional[RoPEMatch]: + """Detect any supported RoPE variant at a given node.""" + return _detect_neox_rope(node) + + +# Graph Surgery + + +def _replace_with_fused_op( + graph: Graph, + sdpa_node: Node, + pre_rope_q: Node, + pre_rope_k: Node, + v_input: Node, + cos_node: Node, + sin_node: Node, + is_causal: bool, + scale: float, + enable_gqa: bool, + rope_interleaved: bool, + rope_sdpa_op, +) -> None: + """Replace an SDPA node with a fused RoPE+SDPA custom op.""" + with graph.inserting_before(sdpa_node): + fused_node = graph.call_function( + rope_sdpa_op, + args=(pre_rope_q, pre_rope_k, v_input, cos_node, sin_node), + kwargs={ + "is_causal": is_causal, + "scale": scale, + "enable_gqa": enable_gqa, + "rope_interleaved": rope_interleaved, + }, + ) + + fused_node.meta = sdpa_node.meta.copy() + sdpa_node.replace_all_uses_with(fused_node) + + logger.info( + "Fused RoPE + SDPA: replaced %s with %s", + sdpa_node.name, + fused_node.name, + ) + + +# Main Fusion Pass + + +def rope_sdpa_fusion_pass( + graph: Graph, + rope_sdpa_op, + fp8_sdpa_op, + backend_name: str = "FP8", +) -> None: + """Detect RoPE patterns preceding FP8 SDPA nodes and fuse them. + + Scans the FX graph for FP8 SDPA custom op nodes (placed by the + monkey-patch). For each one where RoPE is detected on Q and K, + replaces it with the fused RoPE+SDPA custom op. Nodes without + RoPE are left as-is — they are already low-precision from the + monkey-patch. + + Supported patterns: + - Pattern A (RoPE -> transpose -> FP8 SDPA): FLUX-style + - Pattern B (transpose -> RoPE -> FP8 SDPA): HuggingFace-style + + Note: KV caching must be disabled before compilation. + DynamicCache.update() inserts torch.cat nodes that break pattern matching. + """ + fp8_sdpa_nodes = [n for n in graph.nodes if _is_fp8_sdpa_node(n, fp8_sdpa_op)] + + if not fp8_sdpa_nodes: + print( + f"[low_precision_attention] RoPE fusion pass ({backend_name}): " + f"found 0 FP8 SDPA nodes in graph" + ) + return + + fused_count = 0 + + for sdpa_node in fp8_sdpa_nodes: + is_causal, scale, enable_gqa = _get_fp8_sdpa_params(sdpa_node) + + qkv = _get_fp8_sdpa_qkv(sdpa_node) + if qkv is None: + continue + q_node, k_node, v_node = qkv + + v_pre_transpose = _unwrap_transpose(v_node) + + # Pattern A: RoPE -> transpose -> FP8 SDPA (FLUX-style) + q_pre_transpose = _unwrap_transpose(q_node) + k_pre_transpose = _unwrap_transpose(k_node) + + if q_pre_transpose is not None and k_pre_transpose is not None: + q_pre_cast = _trace_through_views(q_pre_transpose) + k_pre_cast = _trace_through_views(k_pre_transpose) + + q_rope = _detect_rope(q_pre_cast) + k_rope = _detect_rope(k_pre_cast) + + if q_rope is not None and k_rope is not None: + pre_rope_q = _trace_through_views(q_rope.pre_rope_input) + pre_rope_k = _trace_through_views(k_rope.pre_rope_input) + + if v_pre_transpose is None: + logger.debug( + "Pattern A: V has no transpose, skipping: %s", + sdpa_node.name, + ) + continue + + cos_sin = _reshape_cos_sin_to_2d( + graph, + q_rope.cos_node, + q_rope.sin_node, + sdpa_node, + ) + if cos_sin is None: + logger.debug( + "Pattern A: cos/sin shape incompatible, skipping: %s", + sdpa_node.name, + ) + continue + cos_2d, sin_2d = cos_sin + + _replace_with_fused_op( + graph=graph, + sdpa_node=sdpa_node, + pre_rope_q=pre_rope_q, + pre_rope_k=pre_rope_k, + v_input=v_pre_transpose, + cos_node=cos_2d, + sin_node=sin_2d, + is_causal=is_causal, + scale=scale, + enable_gqa=enable_gqa, + rope_interleaved=q_rope.rope_interleaved, + rope_sdpa_op=rope_sdpa_op, + ) + fused_count += 1 + continue + + # Pattern B: transpose -> RoPE -> FP8 SDPA (HuggingFace-style) + # For GQA, K may go through repeat_kv after RoPE. + q_rope = _detect_rope(_trace_through_views(q_node)) + + k_rope = _detect_rope(_trace_through_views(k_node)) + gqa_unwrapped = False + if k_rope is None: + k_pre_repeat = _unwrap_repeat_kv(k_node) + if k_pre_repeat is not None: + k_rope = _detect_rope(_trace_through_views(k_pre_repeat)) + if k_rope is not None: + gqa_unwrapped = True + + if q_rope is not None and k_rope is not None: + q_bshd = _unwrap_transpose(_trace_through_views(q_rope.pre_rope_input)) + k_bshd = _unwrap_transpose(_trace_through_views(k_rope.pre_rope_input)) + + if q_bshd is not None and k_bshd is not None: + v_for_fusion = v_node + if gqa_unwrapped: + v_pre_repeat = _unwrap_repeat_kv(v_node) + if v_pre_repeat is not None: + v_for_fusion = v_pre_repeat + + v_bshd = _unwrap_transpose(v_for_fusion) + if v_bshd is None: + logger.debug( + "Pattern B: V has no transpose, skipping: %s", + sdpa_node.name, + ) + continue + + cos_sin = _reshape_cos_sin_to_2d( + graph, + q_rope.cos_node, + q_rope.sin_node, + sdpa_node, + ) + if cos_sin is None: + logger.debug( + "Pattern B: cos/sin shape incompatible, skipping: %s", + sdpa_node.name, + ) + continue + cos_2d, sin_2d = cos_sin + + fused_enable_gqa = True if gqa_unwrapped else enable_gqa + + _replace_with_fused_op( + graph=graph, + sdpa_node=sdpa_node, + pre_rope_q=q_bshd, + pre_rope_k=k_bshd, + v_input=v_bshd, + cos_node=cos_2d, + sin_node=sin_2d, + is_causal=is_causal, + scale=scale, + enable_gqa=fused_enable_gqa, + rope_interleaved=q_rope.rope_interleaved, + rope_sdpa_op=rope_sdpa_op, + ) + fused_count += 1 + continue + + print( + f"[low_precision_attention] RoPE fusion pass ({backend_name}): " + f"found {len(fp8_sdpa_nodes)} FP8 SDPA node(s), " + f"{fused_count} fused with RoPE" + ) + + if fused_count > 0: + graph.eliminate_dead_code() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/setup.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..ad9c02feb8f5f973846c77ff1faec70d97dab366 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/setup.py @@ -0,0 +1,44 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +from functools import partial + +import torch._inductor.config as inductor_config +import torch.nn as nn + +from torchao.prototype.attention.shared_utils.fusion_utils import ( + detect_causal_mask, + rope_sdpa_fusion_pass, +) +from torchao.prototype.attention.shared_utils.wrapper import ( + _FP8FlashAttentionMonkeyPatchWrapper, + _make_causal_aware_sdpa, +) + + +def setup_fp8_backend( + model: nn.Module, + flash_impl_name: str, +) -> nn.Module: + if flash_impl_name == "FA3": + from torchao.prototype.attention.fp8_fa3.attention import _ops + else: + raise ValueError(f"Unknown flash_impl_name: {flash_impl_name}") + + strip_causal_mask = detect_causal_mask(model, flash_impl_name=flash_impl_name) + + inductor_config.pre_grad_custom_pass = partial( + rope_sdpa_fusion_pass, + rope_sdpa_op=_ops.rope_sdpa_op, + fp8_sdpa_op=_ops.fp8_sdpa_op, + backend_name=flash_impl_name, + ) + + return _FP8FlashAttentionMonkeyPatchWrapper( + model, + flash_impl_name=flash_impl_name, + sdpa_patch_fn=_make_causal_aware_sdpa(_ops.fp8_sdpa_op, strip_causal_mask), + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/wrapper.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..25244d51781ff455c3baf5f1478ba7fece0df851 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/wrapper.py @@ -0,0 +1,90 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +from typing import Callable + +import torch.nn as nn +import torch.nn.functional as F +from torch.nn.attention import ( + activate_flash_attention_impl, + restore_flash_attention_impl, +) + + +class _LowPrecisionAttentionWrapper(nn.Module): + """Base wrapper. Proxies attribute access to the original module.""" + + def __init__(self, orig_mod: nn.Module): + super().__init__() + self._orig_mod = orig_mod + + def __getattr__(self, name: str): + try: + return super().__getattr__(name) + except AttributeError: + return getattr(self._orig_mod, name) + + +class _FP8FlashAttentionMonkeyPatchWrapper(_LowPrecisionAttentionWrapper): + """Monkey-patch path wrapper. Replaces ``F.scaled_dot_product_attention`` + with the FP8 backend for the duration of each forward call. + """ + + def __init__( + self, orig_mod: nn.Module, flash_impl_name: str, sdpa_patch_fn: Callable + ): + super().__init__(orig_mod) + self._flash_impl_name = flash_impl_name + self._sdpa_patch_fn = sdpa_patch_fn + + def forward(self, *args, **kwargs): + activate_flash_attention_impl(self._flash_impl_name) + try: + original_sdpa = F.scaled_dot_product_attention + F.scaled_dot_product_attention = self._sdpa_patch_fn + try: + return self._orig_mod(*args, **kwargs) + finally: + F.scaled_dot_product_attention = original_sdpa + finally: + restore_flash_attention_impl() + + +def _make_causal_aware_sdpa(fp8_sdpa_custom_op, strip_causal_mask: bool) -> Callable: + """Bridge F.sdpa signature to the FP8 SDPA custom op. + + Calls the custom op so torch.compile sees an opaque node in the FX graph. + """ + + def _patched( + query, + key, + value, + attn_mask=None, + dropout_p=0.0, + is_causal=False, + scale=None, + enable_gqa=False, + ): + if strip_causal_mask and attn_mask is not None: + attn_mask = None + is_causal = True + if attn_mask is not None: + raise ValueError("attn_mask not supported for FP8 attention") + if dropout_p != 0.0: + raise ValueError( + f"dropout_p must be 0.0 for FP8 attention, got {dropout_p}" + ) + return fp8_sdpa_custom_op( + query, + key, + value, + is_causal=is_causal, + scale=scale if scale is not None else 0.0, + enable_gqa=enable_gqa, + ) + + return _patched diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/blockwise_fp8_training/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/blockwise_fp8_training/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..396608616ac47e72e99a7dc1cce1c646af92c95b Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/blockwise_fp8_training/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/blockwise_fp8_training/__pycache__/kernels.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/blockwise_fp8_training/__pycache__/kernels.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a569763ea822a78f038d5e3f4faf4305782b923f Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/blockwise_fp8_training/__pycache__/kernels.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/blockwise_fp8_training/__pycache__/linear.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/blockwise_fp8_training/__pycache__/linear.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1499be01691cfba35e7c4b9257e3b79b7902d613 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/blockwise_fp8_training/__pycache__/linear.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..054a2db7ab69e6c19492aed72abcafe5c3efbee4 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/__pycache__/float8nocompile_linear.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/__pycache__/float8nocompile_linear.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5ccd15707a9e32beb585cf02081653970023b35 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/__pycache__/float8nocompile_linear.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/__pycache__/float8nocompile_linear_test.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/__pycache__/float8nocompile_linear_test.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..229857141d367be069b6c31b2d14e3d7ea9d2087 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/__pycache__/float8nocompile_linear_test.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/__pycache__/float8nocompile_linear_utils.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/__pycache__/float8nocompile_linear_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05b4dcd1cd46d25627dd501ceb0fd008a4b63535 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/__pycache__/float8nocompile_linear_utils.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/__pycache__/float8nocompile_scaling_utils.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/__pycache__/float8nocompile_scaling_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f84d866fb8e16f6443b340328cb68d88272b602c Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/__pycache__/float8nocompile_scaling_utils.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/kernels/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/kernels/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/kernels/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/kernels/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8868c04d1837b3895c745da54f43143baa0e9288 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/kernels/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/kernels/__pycache__/fp8_dynamic_tensorwise.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/kernels/__pycache__/fp8_dynamic_tensorwise.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2e325f882513c87588c3517082ee4e8186b09d0 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/kernels/__pycache__/fp8_dynamic_tensorwise.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/kernels/__pycache__/fp8_dynamic_tensorwise_test.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/kernels/__pycache__/fp8_dynamic_tensorwise_test.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5e54ea6ed672077a7730a893a1b0e85bcedb208 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/kernels/__pycache__/fp8_dynamic_tensorwise_test.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/kernels/fp8_dynamic_tensorwise.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/kernels/fp8_dynamic_tensorwise.py new file mode 100644 index 0000000000000000000000000000000000000000..9939a1483ab94579a57645b4121b00eef94b9497 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/kernels/fp8_dynamic_tensorwise.py @@ -0,0 +1,1090 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +""" +Triton kernels for scaling high precision tensors to float8. +""" + +from enum import Enum + +import torch +import triton +import triton.language as tl + +from torchao.float8.float8_training_tensor import ( + Float8TrainingTensor, + GemmInputRole, + LinearMMConfig, +) + +EPS = 1e-12 + +FP8_DTYPE_MAP = { + torch.int8: tl.int8, + torch.int16: tl.int16, + torch.int32: tl.int32, + torch.int64: tl.int64, + torch.float8_e4m3fn: tl.float8e4nv, + torch.float8_e5m2: tl.float8e5, + torch.float16: tl.float16, + torch.bfloat16: tl.bfloat16, + torch.float32: tl.float32, + torch.float64: tl.float64, +} + + +kernel_configs_1D = [ + triton.Config({"BLOCK_SIZE": 128}, num_warps=1), + triton.Config({"BLOCK_SIZE": 256}, num_warps=2), + triton.Config({"BLOCK_SIZE": 512}, num_warps=4), + triton.Config({"BLOCK_SIZE": 1024}, num_warps=4), + triton.Config({"BLOCK_SIZE": 2048}, num_warps=8), + triton.Config({"BLOCK_SIZE": 4096}, num_warps=8), +] + +kernel_configs_2D = [ + triton.Config({"BLOCK_SIZE_ROWS": 32, "BLOCK_SIZE_COLS": 32}, num_warps=1), + triton.Config({"BLOCK_SIZE_ROWS": 64, "BLOCK_SIZE_COLS": 64}, num_warps=8), + triton.Config({"BLOCK_SIZE_ROWS": 128, "BLOCK_SIZE_COLS": 128}, num_warps=4), +] + + +class KernelAlgorithm(Enum): + """Enum for FP8 conversion strategy.""" + + # use atomic max to compute global amax between blocks + ATOMIC_MAX = "atomic_max" + + # reduce shared buffer containing local block amaxes to find global amax + REDUCTION = "reduction" + + +@triton.autotune(configs=kernel_configs_1D, key=["num_elements"]) +@triton.jit +def _to_fp8_row_major( + input_ptr, + out_ptr, + scale_ptr, + num_elements: int, + fp8_dtype_min: float, + fp8_dtype_max: float, + input_dtype: tl.constexpr, + output_dtype: tl.constexpr, + BLOCK_SIZE: tl.constexpr, + EPS: tl.constexpr, +): + block_id = tl.program_id(axis=0) + + # load scaling factor + scale = tl.load(scale_ptr).to(tl.float32) + + # load block of input tensor + block_start = block_id * BLOCK_SIZE + block_offs = block_start + tl.arange(0, BLOCK_SIZE) + mask = block_offs < num_elements + vals = tl.load(input_ptr + block_offs, mask=mask).to(input_dtype) + + # perform conversion + vals = vals * scale + fp8_vals = tl.clamp(vals, min=fp8_dtype_min, max=fp8_dtype_max).to(output_dtype) + tl.store(out_ptr + block_offs, fp8_vals, mask=mask) + + +@triton.autotune( + configs=kernel_configs_2D, + key=["num_elements"], +) +@triton.jit +def _to_fp8_row_major_t( + input_ptr, + out_ptr, + scale_ptr, + num_elements: int, + fp8_dtype_min: float, + fp8_dtype_max: float, + input_num_rows: int, + input_num_cols: int, + output_num_rows: int, + output_num_cols: int, + input_stride_row: int, + input_stride_col: int, + output_stride_row: int, + output_stride_col: int, + input_dtype: tl.constexpr, + output_dtype: tl.constexpr, + BLOCK_SIZE_ROWS: tl.constexpr, + BLOCK_SIZE_COLS: tl.constexpr, + EPS: tl.constexpr, +): + block_row_id = tl.program_id(axis=0) + block_col_id = tl.program_id(axis=1) + + # load scaling factor + scale = tl.load(scale_ptr).to(tl.float32) + + # load block of input tensor + block_row_start = block_row_id * BLOCK_SIZE_ROWS + block_col_start = block_col_id * BLOCK_SIZE_COLS + block_row_offs = block_row_start + tl.arange(0, BLOCK_SIZE_ROWS) + block_col_offs = block_col_start + tl.arange(0, BLOCK_SIZE_COLS) + input_offs = ( + block_row_offs[:, None] * input_stride_row + + block_col_offs[None, :] * input_stride_col + ) + input_mask = (block_row_offs[:, None] < input_num_rows) & ( + block_col_offs[None, :] < input_num_cols + ) + vals = tl.load(input_ptr + input_offs, mask=input_mask).to(input_dtype) + + # perform conversion + vals = vals * scale + fp8_vals = tl.clamp(vals, min=fp8_dtype_min, max=fp8_dtype_max).to(output_dtype) + + # write back in tranposed output tensor + out_offs = ( + block_col_offs[:, None] * output_stride_row + + block_row_offs[None, :] * output_stride_col + ) + out_mask = (block_row_offs[:, None] < output_num_rows) & ( + block_col_offs[None, :] < output_num_cols + ) + tl.store(out_ptr + out_offs, fp8_vals.trans(1, 0), mask=out_mask) + + +@triton.autotune( + configs=kernel_configs_2D, + key=["num_elements"], +) +@triton.jit +def _to_fp8_col_major( + input_ptr, + out_ptr, + scale_ptr, + num_elements: int, + fp8_dtype_min: float, + fp8_dtype_max: float, + num_rows: int, + num_cols: int, + out_stride_row: int, + out_stride_col: int, + input_dtype: tl.constexpr, + output_dtype: tl.constexpr, + BLOCK_SIZE_ROWS: tl.constexpr, + BLOCK_SIZE_COLS: tl.constexpr, + EPS: tl.constexpr, +): + block_row_id = tl.program_id(axis=0) + block_col_id = tl.program_id(axis=1) + + # load scaling factor + scale = tl.load(scale_ptr).to(tl.float32) + + # load block of input tensor + block_row_start = block_row_id * BLOCK_SIZE_ROWS + block_col_start = block_col_id * BLOCK_SIZE_COLS + block_row_offs = block_row_start + tl.arange(0, BLOCK_SIZE_ROWS) + block_col_offs = block_col_start + tl.arange(0, BLOCK_SIZE_COLS) + block_offs = block_row_offs[:, None] * num_cols + block_col_offs[None, :] + mask = (block_row_offs[:, None] < num_rows) & (block_col_offs[None, :] < num_cols) + vals = tl.load(input_ptr + block_offs, mask=mask).to(input_dtype) + + # perform conversion + vals = vals * scale + fp8_vals = tl.clamp(vals, min=fp8_dtype_min, max=fp8_dtype_max).to(output_dtype) + out_offs = block_col_offs[None, :] * num_rows + block_row_offs[:, None] + tl.store(out_ptr + out_offs, fp8_vals, mask=mask) + + +@triton.autotune( + configs=kernel_configs_2D, + key=["num_elements"], +) +@triton.jit +def to_fp8_col_major_t( + input_ptr, + out_ptr, + scale_ptr, + num_elements: int, + fp8_dtype_min: float, + fp8_dtype_max: float, + input_num_rows: int, + input_num_cols: int, + output_num_rows: int, + output_num_cols: int, + input_stride_row: int, + input_stride_col: int, + output_stride_row: int, + output_stride_col: int, + input_dtype: tl.constexpr, + output_dtype: tl.constexpr, + BLOCK_SIZE_ROWS: tl.constexpr, + BLOCK_SIZE_COLS: tl.constexpr, + EPS: tl.constexpr, +): + block_row_id = tl.program_id(axis=0) + block_col_id = tl.program_id(axis=1) + + # load scaling factor + scale = tl.load(scale_ptr).to(tl.float32) + + # load block of input tensor + block_row_start = block_row_id * BLOCK_SIZE_ROWS + block_col_start = block_col_id * BLOCK_SIZE_COLS + block_row_offs = block_row_start + tl.arange(0, BLOCK_SIZE_ROWS) + block_col_offs = block_col_start + tl.arange(0, BLOCK_SIZE_COLS) + input_offs = ( + block_row_offs[:, None] * input_stride_row + + block_col_offs[None, :] * input_stride_col + ) + input_mask = (block_row_offs[:, None] < input_num_rows) & ( + block_col_offs[None, :] < input_num_cols + ) + vals = tl.load(input_ptr + input_offs, mask=input_mask).to(input_dtype) + + # perform conversion + vals = vals * scale + fp8_vals = tl.clamp(vals, min=fp8_dtype_min, max=fp8_dtype_max).to(output_dtype) + fp8_vals = fp8_vals.trans(1, 0) + + # write back in tranposed output tensor + out_offs = ( + block_col_offs[:, None] * output_stride_row + + block_row_offs[None, :] * output_stride_col + ) + out_mask = (block_col_offs[:, None] < output_num_rows) & ( + block_row_offs[None, :] < output_num_cols + ) + tl.store(out_ptr + out_offs, fp8_vals, mask=out_mask) + + +@triton.autotune( + configs=kernel_configs_2D, + key=["num_elements"], +) +@triton.jit +def _to_fp8_row_and_col_major( + input_ptr, + row_major_out_ptr, + col_major_out_ptr, + scale_ptr, + num_elements: int, + fp8_dtype_min: float, + fp8_dtype_max: float, + num_rows: int, + num_cols: int, + input_dtype: tl.constexpr, + output_dtype: tl.constexpr, + BLOCK_SIZE_ROWS: tl.constexpr, + BLOCK_SIZE_COLS: tl.constexpr, + EPS: tl.constexpr, +): + block_row_id = tl.program_id(axis=0) + block_col_id = tl.program_id(axis=1) + + # load scaling factor + scale = tl.load(scale_ptr).to(tl.float32) + + # load block of input tensor + block_row_start = block_row_id * BLOCK_SIZE_ROWS + block_col_start = block_col_id * BLOCK_SIZE_COLS + block_row_offs = block_row_start + tl.arange(0, BLOCK_SIZE_ROWS) + block_col_offs = block_col_start + tl.arange(0, BLOCK_SIZE_COLS) + block_offs = block_row_offs[:, None] * num_cols + block_col_offs[None, :] + mask = (block_row_offs[:, None] < num_rows) & (block_col_offs[None, :] < num_cols) + vals = tl.load(input_ptr + block_offs, mask=mask).to(input_dtype) + + # perform conversion + vals = vals * scale + fp8_vals = tl.clamp(vals, min=fp8_dtype_min, max=fp8_dtype_max).to(output_dtype) + + # write row major output + row_major_offs = block_row_offs[:, None] * num_cols + block_col_offs[None, :] + tl.store(row_major_out_ptr + row_major_offs, fp8_vals, mask=mask) + + # write column major output + col_major_offs = block_col_offs[None, :] * num_rows + block_row_offs[:, None] + tl.store(col_major_out_ptr + col_major_offs, fp8_vals, mask=mask) + + +@triton.autotune( + configs=kernel_configs_2D, + key=["num_elements"], +) +@triton.jit +def _to_fp8_row_major_t_and_non_t( + input_ptr, + row_major_out_ptr, + row_major_t_out_ptr, + scale_ptr, + num_elements: int, + fp8_dtype_min: float, + fp8_dtype_max: float, + input_num_rows: int, + input_num_cols: int, + input_stride_row: int, + input_stride_col: int, + row_major_out_stride_row: int, + row_major_out_stride_col: int, + row_major_t_out_stride_row: int, + row_major_t_out_stride_col: int, + input_dtype: tl.constexpr, + output_dtype: tl.constexpr, + BLOCK_SIZE_ROWS: tl.constexpr, + BLOCK_SIZE_COLS: tl.constexpr, + EPS: tl.constexpr, +): + """ + Reads a row-major, high precision input tensor and writes 2 output tensors: + 1) fp8 row major tensor (transposed) + 2) fp8 row major tensor + """ + block_row_id = tl.program_id(axis=0) + block_col_id = tl.program_id(axis=1) + + # load scaling factor + scale = tl.load(scale_ptr).to(tl.float32) + + # load block of input tensor + block_row_start = block_row_id * BLOCK_SIZE_ROWS + block_col_start = block_col_id * BLOCK_SIZE_COLS + block_row_offs = block_row_start + tl.arange(0, BLOCK_SIZE_ROWS) + block_col_offs = block_col_start + tl.arange(0, BLOCK_SIZE_COLS) + input_offs = ( + block_row_offs[:, None] * input_stride_row + + block_col_offs[None, :] * input_stride_col + ) + mask = (block_row_offs[:, None] < input_num_rows) & ( + block_col_offs[None, :] < input_num_cols + ) + vals = tl.load(input_ptr + input_offs, mask=mask).to(input_dtype) + + # perform conversion + vals = vals * scale + fp8_vals = tl.clamp(vals, min=fp8_dtype_min, max=fp8_dtype_max).to(output_dtype) + + # write row-major output + row_major_offs = ( + block_row_offs[:, None] * row_major_out_stride_row + + block_col_offs[None, :] * row_major_out_stride_col + ) + tl.store(row_major_out_ptr + row_major_offs, fp8_vals, mask=mask) + + # write tranposed row-major output + row_major_t_num_rows = input_num_cols + row_major_t_num_cols = input_num_rows + row_major_t_offs = ( + block_col_offs[:, None] * row_major_t_out_stride_row + + block_row_offs[None, :] * row_major_t_out_stride_col + ) + mask = (block_col_offs[:, None] < row_major_t_num_rows) & ( + block_row_offs[None, :] < row_major_t_num_cols + ) + tl.store(row_major_t_out_ptr + row_major_t_offs, fp8_vals.trans(1, 0), mask=mask) + + +@triton.autotune(configs=kernel_configs_2D, key=["num_elements"]) +@triton.jit +def _to_fp8_col_major_t_and_non_t( + input_ptr, + col_major_out_ptr, + col_major_t_out_ptr, + scale_ptr, + num_elements: int, + fp8_dtype_min: float, + fp8_dtype_max: float, + input_num_rows: int, + input_num_cols: int, + input_stride_row: int, + input_stride_col: int, + col_major_out_stride_row: int, + col_major_out_stride_col: int, + col_major_t_out_stride_row: int, + col_major_t_out_stride_col: int, + input_dtype: tl.constexpr, + output_dtype: tl.constexpr, + BLOCK_SIZE_ROWS: tl.constexpr, + BLOCK_SIZE_COLS: tl.constexpr, + EPS: tl.constexpr, +): + """ + Reads a row-major, high precision input tensor and writes 2 output tensors: + 1) fp8 col major tensor (transposed) + 2) fp8 col major tensor + """ + # col major tranposed + block_row_id = tl.program_id(axis=0) + block_col_id = tl.program_id(axis=1) + + # load scaling factor + scale = tl.load(scale_ptr).to(tl.float32) + + # load block of input tensor + block_row_start = block_row_id * BLOCK_SIZE_ROWS + block_col_start = block_col_id * BLOCK_SIZE_COLS + block_row_offs = block_row_start + tl.arange(0, BLOCK_SIZE_ROWS) + block_col_offs = block_col_start + tl.arange(0, BLOCK_SIZE_COLS) + input_offs = ( + block_row_offs[:, None] * input_stride_row + + block_col_offs[None, :] * input_stride_col + ) + mask = (block_row_offs[:, None] < input_num_rows) & ( + block_col_offs[None, :] < input_num_cols + ) + vals = tl.load(input_ptr + input_offs, mask=mask).to(input_dtype) + + # perform conversion + vals = vals * scale + fp8_vals = tl.clamp(vals, min=fp8_dtype_min, max=fp8_dtype_max).to(output_dtype) + + # 1. write col-major output + out_offs = block_row_offs[:, None] + block_col_offs[None, :] * input_num_rows + tl.store(col_major_out_ptr + out_offs, fp8_vals, mask=mask) + + # 2. write tranposed col-major output + col_major_t_num_rows = input_num_cols + col_major_t_num_cols = input_num_rows + out_offs = ( + block_col_offs[:, None] * col_major_t_out_stride_row + + block_row_offs[None, :] * col_major_t_out_stride_col + ) + out_mask = (block_col_offs[:, None] < col_major_t_num_rows) & ( + block_row_offs[None, :] < col_major_t_num_cols + ) + tl.store(col_major_t_out_ptr + out_offs, fp8_vals.trans(1, 0), mask=out_mask) + + +@triton.autotune(configs=kernel_configs_1D, key=["num_elements"]) +@triton.jit +def _amax_atomic( + input_ptr, + amax_ptr, + num_elements, + input_dtype: tl.constexpr, + BLOCK_SIZE: tl.constexpr, + EPS: tl.constexpr, +): + # compute local amax for each block + block_id = tl.program_id(axis=0) + block_start = block_id * BLOCK_SIZE + block_offs = block_start + tl.arange(0, BLOCK_SIZE) + block_mask = block_offs < num_elements + vals = tl.load(input_ptr + block_offs, mask=block_mask).to(input_dtype) + block_amax = tl.max(tl.abs(vals)) + # AMD GPUs need relaxed semantics for better performance + if tl.constexpr(torch.version.hip is not None): + tl.atomic_max(amax_ptr, block_amax, sem="relaxed") + else: + tl.atomic_max(amax_ptr, block_amax) + + +@triton.jit +def _scale_atomic( + amax_ptr, + scale_out_ptr, + fp8_dtype_max, + EPS: tl.constexpr, +): + # load previously computed global amax + global_amax = tl.load(amax_ptr).to(tl.float64) + + # compute scale, must be fp32 + scale = (fp8_dtype_max / tl.clamp(global_amax, min=EPS, max=float("inf"))).to( + tl.float32 + ) + + # store scale for use in Float8TrainingTensor constructor + scale_off = tl.arange(0, 1) + tl.store(scale_out_ptr + scale_off, scale) + + +@triton.jit +def _amax_reduction( + input_ptr, + block_amaxes_ptr, + num_elements, + input_dtype: tl.constexpr, + BLOCK_SIZE: tl.constexpr, + EPS: tl.constexpr, +): + # compute local amax for each block + block_id = tl.program_id(axis=0) + block_start = block_id * BLOCK_SIZE + block_offs = block_start + tl.arange(0, BLOCK_SIZE) + block_mask = block_offs < num_elements + vals = tl.load(input_ptr + block_offs, mask=block_mask).to(input_dtype) + block_amax = tl.max(tl.abs(vals)) + tl.store(block_amaxes_ptr + block_id, block_amax) + + +@triton.jit +def _scale_reduction( + block_amaxes_ptr, + scale_out_ptr, + num_elements, + fp8_dtype_max, + BLOCK_SIZE: tl.constexpr, + EPS: tl.constexpr, +): + # calculate global amax across all blocks + global_amax = tl.zeros([1], dtype=tl.float64) + num_blocks = tl.cdiv(num_elements, BLOCK_SIZE) + for i in range(num_blocks): + block_max = tl.load(block_amaxes_ptr + i) + global_amax = tl.maximum(global_amax, block_max) + + # compute scale, must be fp32 + scale = (fp8_dtype_max / tl.clamp(global_amax, min=EPS, max=float("inf"))).to( + tl.float32 + ) + scale_off = tl.arange(0, 1) + tl.store(scale_out_ptr + scale_off, scale) + + +def hp_to_fp8_row_major( + hp_tensor: torch.Tensor, + fp8_dtype: torch.dtype, + linear_mm_config: LinearMMConfig, + gemm_input_role: GemmInputRole = GemmInputRole.INPUT, + algo: KernelAlgorithm = KernelAlgorithm.ATOMIC_MAX, +) -> Float8TrainingTensor: + assert hp_tensor.is_contiguous(), "input tensor must be contiguous" + + num_elements = hp_tensor.numel() + tl_input_dtype = FP8_DTYPE_MAP[hp_tensor.dtype] + tl_output_dtype = FP8_DTYPE_MAP[fp8_dtype] + + fp8_dtype_min = torch.finfo(fp8_dtype).min + fp8_dtype_max = torch.finfo(fp8_dtype).max + + # compute scaling factor for tensor + scale = _hp_tensor_to_scale( + hp_tensor, + tl_input_dtype, + fp8_dtype_max, + algo, + ) + + # perform fp8 conversion + output_buffer = torch.empty_like( + hp_tensor, dtype=fp8_dtype, device=hp_tensor.device + ) + grid = lambda meta: (triton.cdiv(num_elements, meta["BLOCK_SIZE"]),) + _to_fp8_row_major[grid]( + hp_tensor, + output_buffer, + scale, + num_elements, + fp8_dtype_min, + fp8_dtype_max, + tl_input_dtype, + tl_output_dtype, + EPS=EPS, + ) + + # wrap output tensor in Float8TrainingTensor + fp8_tensor_row_major = Float8TrainingTensor( + output_buffer, + scale, + orig_dtype=hp_tensor.dtype, + linear_mm_config=linear_mm_config, + gemm_input_role=gemm_input_role, + ) + return fp8_tensor_row_major + + +def hp_to_fp8_row_major_t( + hp_tensor: torch.Tensor, + fp8_dtype: torch.dtype, + linear_mm_config: LinearMMConfig, + gemm_input_role: GemmInputRole = GemmInputRole.INPUT, + algo: KernelAlgorithm = KernelAlgorithm.ATOMIC_MAX, +) -> Float8TrainingTensor: + assert hp_tensor.is_contiguous(), "input tensor must be contiguous" + + num_elements = hp_tensor.numel() + input_num_rows, input_num_cols = hp_tensor.shape + output_num_rows, output_num_cols = input_num_cols, input_num_rows + tl_input_dtype = FP8_DTYPE_MAP[hp_tensor.dtype] + tl_output_dtype = FP8_DTYPE_MAP[fp8_dtype] + + fp8_dtype_min = torch.finfo(fp8_dtype).min + fp8_dtype_max = torch.finfo(fp8_dtype).max + + # compute scaling factor for tensor + scale = _hp_tensor_to_scale( + hp_tensor, + tl_input_dtype, + fp8_dtype_max, + algo, + ) + + # perform conversion + output_buffer = torch.empty( + (output_num_rows, output_num_cols), dtype=fp8_dtype, device=hp_tensor.device + ) + grid = lambda meta: ( + triton.cdiv(input_num_rows, meta["BLOCK_SIZE_ROWS"]), + triton.cdiv(input_num_cols, meta["BLOCK_SIZE_COLS"]), + ) + _to_fp8_row_major_t[grid]( + hp_tensor, + output_buffer, + scale, + num_elements, + fp8_dtype_min, + fp8_dtype_max, + input_num_rows, + input_num_cols, + output_num_rows, + output_num_cols, + hp_tensor.stride(0), + hp_tensor.stride(1), + output_buffer.stride(0), + output_buffer.stride(1), + input_dtype=tl_input_dtype, + output_dtype=tl_output_dtype, + EPS=EPS, + ) + + # wrap output tensor in Float8TrainingTensor + fp8_tensor_row_major_t = Float8TrainingTensor( + output_buffer, + scale, + orig_dtype=hp_tensor.dtype, + linear_mm_config=linear_mm_config, + gemm_input_role=gemm_input_role, + ) + return fp8_tensor_row_major_t + + +def hp_to_fp8_col_major( + hp_tensor: torch.Tensor, + fp8_dtype: torch.dtype, + linear_mm_config: LinearMMConfig, + gemm_input_role: GemmInputRole = GemmInputRole.INPUT, + algo: KernelAlgorithm = KernelAlgorithm.ATOMIC_MAX, +) -> Float8TrainingTensor: + assert hp_tensor.is_contiguous(), "input tensor must be contiguous" + + num_elements = hp_tensor.numel() + num_rows, num_cols = hp_tensor.shape + tl_input_dtype = FP8_DTYPE_MAP[hp_tensor.dtype] + tl_output_dtype = FP8_DTYPE_MAP[fp8_dtype] + + fp8_dtype_min = torch.finfo(fp8_dtype).min + fp8_dtype_max = torch.finfo(fp8_dtype).max + + # compute scaling factor for tensor + scale = _hp_tensor_to_scale( + hp_tensor, + tl_input_dtype, + fp8_dtype_max, + algo, + ) + + # perform fp8 conversion + output_buffer = torch.empty_like( + hp_tensor, dtype=fp8_dtype, device=hp_tensor.device + ) + grid = lambda meta: ( + triton.cdiv(num_rows, meta["BLOCK_SIZE_ROWS"]), + triton.cdiv(num_cols, meta["BLOCK_SIZE_COLS"]), + ) + _to_fp8_col_major[grid]( + hp_tensor, + output_buffer, + scale, + num_elements, + fp8_dtype_min, + fp8_dtype_max, + num_rows, + num_cols, + output_buffer.stride(0), + output_buffer.stride(1), + input_dtype=tl_input_dtype, + output_dtype=tl_output_dtype, + EPS=EPS, + ) + + # for col major we need to update the strides to reflect the new memory layout + col_major_strides = (1, num_rows) + output_buffer = output_buffer.as_strided(output_buffer.size(), col_major_strides) + + # wrap output tensor in Float8TrainingTensor + fp8_tensor_col_major = Float8TrainingTensor( + output_buffer, + scale, + orig_dtype=hp_tensor.dtype, + linear_mm_config=linear_mm_config, + gemm_input_role=gemm_input_role, + ) + return fp8_tensor_col_major + + +def hp_to_fp8_col_major_t( + hp_tensor: torch.Tensor, + fp8_dtype: torch.dtype, + linear_mm_config: LinearMMConfig, + gemm_input_role: GemmInputRole = GemmInputRole.INPUT, + algo: KernelAlgorithm = KernelAlgorithm.ATOMIC_MAX, +) -> Float8TrainingTensor: + assert hp_tensor.is_contiguous(), "input tensor must be contiguous" + + num_elements = hp_tensor.numel() + tl_input_dtype = FP8_DTYPE_MAP[hp_tensor.dtype] + tl_output_dtype = FP8_DTYPE_MAP[fp8_dtype] + + fp8_dtype_min = torch.finfo(fp8_dtype).min + fp8_dtype_max = torch.finfo(fp8_dtype).max + + # compute scaling factor for tensor + scale = _hp_tensor_to_scale( + hp_tensor, + tl_input_dtype, + fp8_dtype_max, + algo, + ) + + # perform conversion + output_buffer = torch.empty_like( + hp_tensor.t(), dtype=fp8_dtype, device=hp_tensor.device + ) + grid = lambda meta: (triton.cdiv(num_elements, meta["BLOCK_SIZE"]),) + _to_fp8_row_major[grid]( + hp_tensor, + output_buffer, + scale, + num_elements, + fp8_dtype_min, + fp8_dtype_max, + tl_input_dtype, + tl_output_dtype, + EPS=EPS, + ) + + # wrap output tensor in Float8TrainingTensor + fp8_tensor_col_major_t = Float8TrainingTensor( + output_buffer, + scale, + orig_dtype=hp_tensor.dtype, + linear_mm_config=linear_mm_config, + gemm_input_role=gemm_input_role, + ) + return fp8_tensor_col_major_t + + +def hp_to_fp8_row_and_col_major( + hp_tensor: torch.Tensor, + fp8_dtype: torch.dtype, + linear_mm_config: LinearMMConfig, + gemm_input_role: GemmInputRole = GemmInputRole.INPUT, + algo: KernelAlgorithm = KernelAlgorithm.ATOMIC_MAX, +) -> Float8TrainingTensor: + assert hp_tensor.is_contiguous(), "input tensor must be contiguous" + + tl_input_dtype = FP8_DTYPE_MAP[hp_tensor.dtype] + tl_output_dtype = FP8_DTYPE_MAP[fp8_dtype] + + fp8_dtype_min = torch.finfo(fp8_dtype).min + fp8_dtype_max = torch.finfo(fp8_dtype).max + + # compute scaling factor for tensor + scale = _hp_tensor_to_scale( + hp_tensor, + tl_input_dtype, + fp8_dtype_max, + algo, + ) + + # perform fp8 conversion + orig_shape = hp_tensor.shape + num_elements = hp_tensor.numel() + + # preallocate necessary output tensors + fp8_output_row_major = torch.empty( + orig_shape, dtype=fp8_dtype, device=hp_tensor.device + ) + fp8_output_col_major = torch.empty( + orig_shape, dtype=fp8_dtype, device=hp_tensor.device + ) + + # launch triton kernel to perform conversion + num_rows, num_cols = orig_shape + grid = lambda meta: ( + triton.cdiv(num_rows, meta["BLOCK_SIZE_ROWS"]), + triton.cdiv(num_cols, meta["BLOCK_SIZE_COLS"]), + ) + _to_fp8_row_and_col_major[grid]( + hp_tensor, + fp8_output_row_major, + fp8_output_col_major, + scale, + num_elements, + fp8_dtype_min, + fp8_dtype_max, + num_rows, + num_cols, + input_dtype=tl_input_dtype, + output_dtype=tl_output_dtype, + EPS=EPS, + ) + + # for col major we need to update the strides to reflect the new memory layout + col_major_strides = (1, num_rows) + fp8_output_col_major = fp8_output_col_major.as_strided( + fp8_output_col_major.size(), col_major_strides + ) + + # wrap outputs in Float8TrainingTensors + fp8_tensor_row_major = Float8TrainingTensor( + fp8_output_row_major, + scale, + orig_dtype=hp_tensor.dtype, + linear_mm_config=linear_mm_config, + gemm_input_role=gemm_input_role, + ) + fp8_tensor_col_major = Float8TrainingTensor( + fp8_output_col_major, + scale, + orig_dtype=hp_tensor.dtype, + linear_mm_config=linear_mm_config, + gemm_input_role=gemm_input_role, + ) + return fp8_tensor_row_major, fp8_tensor_col_major + + +def hp_to_fp8_row_major_t_and_non_t( + hp_tensor: torch.Tensor, + fp8_dtype: torch.dtype, + linear_mm_config: LinearMMConfig, + gemm_input_role: GemmInputRole = GemmInputRole.INPUT, + algo: KernelAlgorithm = KernelAlgorithm.ATOMIC_MAX, +) -> Float8TrainingTensor: + assert hp_tensor.is_contiguous(), "input tensor must be contiguous" + + tl_input_dtype = FP8_DTYPE_MAP[hp_tensor.dtype] + tl_output_dtype = FP8_DTYPE_MAP[fp8_dtype] + + fp8_dtype_min = torch.finfo(fp8_dtype).min + fp8_dtype_max = torch.finfo(fp8_dtype).max + + # compute scaling factor for tensor + scale = _hp_tensor_to_scale( + hp_tensor, + tl_input_dtype, + fp8_dtype_max, + algo, + ) + + # perform fp8 conversion + input_num_rows, input_num_cols = hp_tensor.shape + transposed_num_rows, transposed_num_cols = input_num_cols, input_num_rows + num_elements = hp_tensor.numel() + + # preallocate necessary output tensors + fp8_output_row_major = torch.empty( + (input_num_rows, input_num_cols), dtype=fp8_dtype, device=hp_tensor.device + ) + fp8_output_row_major_t = torch.empty( + (transposed_num_rows, transposed_num_cols), + dtype=fp8_dtype, + device=hp_tensor.device, + ) + + # launch triton kernel to perform conversion + grid = lambda meta: ( + triton.cdiv(input_num_rows, meta["BLOCK_SIZE_ROWS"]), + triton.cdiv(input_num_cols, meta["BLOCK_SIZE_COLS"]), + ) + _to_fp8_row_major_t_and_non_t[grid]( + hp_tensor, + fp8_output_row_major, + fp8_output_row_major_t, + scale, + num_elements, + fp8_dtype_min, + fp8_dtype_max, + input_num_rows, + input_num_cols, + hp_tensor.stride(0), + hp_tensor.stride(1), + fp8_output_row_major.stride(0), + fp8_output_row_major.stride(1), + fp8_output_row_major_t.stride(0), + fp8_output_row_major_t.stride(1), + input_dtype=tl_input_dtype, + output_dtype=tl_output_dtype, + EPS=EPS, + ) + + # wrap outputs in Float8TrainingTensors + fp8_tensor_row_major = Float8TrainingTensor( + fp8_output_row_major, + scale, + orig_dtype=hp_tensor.dtype, + linear_mm_config=linear_mm_config, + gemm_input_role=gemm_input_role, + ) + fp8_tensor_row_major_t = Float8TrainingTensor( + fp8_output_row_major_t, + scale, + orig_dtype=hp_tensor.dtype, + linear_mm_config=linear_mm_config, + gemm_input_role=gemm_input_role, + ) + return fp8_tensor_row_major, fp8_tensor_row_major_t + + +def hp_to_fp8_col_major_t_and_non_t( + hp_tensor: torch.Tensor, + fp8_dtype: torch.dtype, + linear_mm_config: LinearMMConfig, + gemm_input_role: GemmInputRole = GemmInputRole.INPUT, + algo: KernelAlgorithm = KernelAlgorithm.ATOMIC_MAX, +) -> Float8TrainingTensor: + assert hp_tensor.is_contiguous(), "input tensor must be contiguous" + + tl_input_dtype = FP8_DTYPE_MAP[hp_tensor.dtype] + tl_output_dtype = FP8_DTYPE_MAP[fp8_dtype] + + fp8_dtype_min = torch.finfo(fp8_dtype).min + fp8_dtype_max = torch.finfo(fp8_dtype).max + + # compute scaling factor for tensor + scale = _hp_tensor_to_scale( + hp_tensor, + tl_input_dtype, + fp8_dtype_max, + algo, + ) + + # perform fp8 conversion + input_num_rows, input_num_cols = hp_tensor.shape + num_elements = hp_tensor.numel() + + # preallocate necessary output tensors + fp8_output_col_major = torch.empty( + (input_num_rows, input_num_cols), dtype=fp8_dtype, device=hp_tensor.device + ) + fp8_output_col_major_t = torch.empty_like( + hp_tensor.t(), + dtype=fp8_dtype, + device=hp_tensor.device, + ) + + # launch triton kernel to perform conversion + grid = lambda meta: ( + triton.cdiv(input_num_rows, meta["BLOCK_SIZE_ROWS"]), + triton.cdiv(input_num_cols, meta["BLOCK_SIZE_COLS"]), + ) + _to_fp8_col_major_t_and_non_t[grid]( + hp_tensor, + fp8_output_col_major, + fp8_output_col_major_t, + scale, + num_elements, + fp8_dtype_min, + fp8_dtype_max, + input_num_rows, + input_num_cols, + hp_tensor.stride(0), + hp_tensor.stride(1), + fp8_output_col_major.stride(0), + fp8_output_col_major.stride(1), + fp8_output_col_major_t.stride(0), + fp8_output_col_major_t.stride(1), + input_dtype=tl_input_dtype, + output_dtype=tl_output_dtype, + EPS=EPS, + ) + + # for col major we need to update the strides to reflect the new memory layout + col_major_strides = (1, input_num_rows) + fp8_output_col_major = fp8_output_col_major.as_strided( + fp8_output_col_major.size(), col_major_strides + ) + + # wrap outputs in Float8TrainingTensors + fp8_tensor_col_major = Float8TrainingTensor( + fp8_output_col_major, + scale, + orig_dtype=hp_tensor.dtype, + linear_mm_config=linear_mm_config, + gemm_input_role=gemm_input_role, + ) + fp8_tensor_col_major_t = Float8TrainingTensor( + fp8_output_col_major_t, + scale, + orig_dtype=hp_tensor.dtype, + linear_mm_config=linear_mm_config, + gemm_input_role=gemm_input_role, + ) + return fp8_tensor_col_major, fp8_tensor_col_major_t + + +def _hp_tensor_to_scale( + hp_tensor: torch.Tensor, + tl_input_dtype: tl.core.dtype, + fp8_dtype_max: float, + algo: KernelAlgorithm, +) -> torch.Tensor: + num_elements = hp_tensor.numel() + scale_out = torch.empty((), dtype=torch.float32, device=hp_tensor.device) + grid = lambda meta: (triton.cdiv(num_elements, meta["BLOCK_SIZE"]),) + + # compute the fp8 scale using the given algorithm + if algo == KernelAlgorithm.ATOMIC_MAX: + global_amax = torch.zeros((1,), dtype=torch.float32, device=hp_tensor.device) + # compute global amax to be used for scaling + _amax_atomic[grid]( + hp_tensor, + global_amax, + num_elements, + input_dtype=tl_input_dtype, + EPS=EPS, + ) + + # compute scale for fp8 conversion + _scale_atomic[1, 1, 1]( + global_amax, + scale_out, + fp8_dtype_max, + EPS=EPS, + ) + + elif algo == KernelAlgorithm.REDUCTION: + # max block size and num warps values determined via manual tuning + max_block_size = 4096 + num_warps = 8 + block_size = triton.next_power_of_2(min(max_block_size, num_elements)) + amax_buffer_size = triton.cdiv(num_elements, block_size) + block_amaxes = torch.zeros( + (amax_buffer_size,), dtype=torch.float32, device=hp_tensor.device + ) + # compute local amax for each block + _amax_reduction[grid]( + hp_tensor, + block_amaxes, + num_elements, + input_dtype=tl_input_dtype, + BLOCK_SIZE=block_size, + EPS=EPS, + num_warps=num_warps, + ) + + # calculate global amax across all blocks and use it to compute scale + _scale_reduction[(1, 1, 1)]( + block_amaxes, + scale_out, + num_elements, + fp8_dtype_max, + BLOCK_SIZE=block_size, + EPS=EPS, + ) + else: + raise ValueError(f"Unsupported kernel algorithm: {algo}") + + return scale_out diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/kernels/fp8_dynamic_tensorwise_test.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/kernels/fp8_dynamic_tensorwise_test.py new file mode 100644 index 0000000000000000000000000000000000000000..0d7a20fae7f153af69d704c056e08f9584ad0af4 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/kernels/fp8_dynamic_tensorwise_test.py @@ -0,0 +1,493 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. +import pytest +import torch + +from torchao.float8.float8_scaling_utils import hp_tensor_to_float8_dynamic +from torchao.float8.float8_training_tensor import LinearMMConfig +from torchao.float8.float8_utils import is_row_major +from torchao.prototype.float8nocompile.kernels.fp8_dynamic_tensorwise import ( + KernelAlgorithm, + hp_to_fp8_col_major, + hp_to_fp8_col_major_t, + hp_to_fp8_col_major_t_and_non_t, + hp_to_fp8_row_and_col_major, + hp_to_fp8_row_major, + hp_to_fp8_row_major_t, + hp_to_fp8_row_major_t_and_non_t, +) + + +@pytest.mark.parametrize( + "algo", + [KernelAlgorithm.REDUCTION, KernelAlgorithm.ATOMIC_MAX], +) +@pytest.mark.parametrize( + "input_shape", + [(2, 4), (32, 16), (512, 512)], +) +def test_fp8_hp_to_fp8_row_major(input_shape: tuple[int, int], algo: KernelAlgorithm): + assert torch.cuda.is_available() + device = "cuda" + input_bf16 = torch.randn(input_shape, dtype=torch.bfloat16, device=device) + x_bf16 = input_bf16.clone().detach().to(device) + y_bf16 = input_bf16.clone().detach().to(device) + + # production implementation + x_fp8_row_major = hp_tensor_to_float8_dynamic( + x_bf16, + torch.float8_e4m3fn, + LinearMMConfig(), + ) + + # float8nocompile triton implementation + y_fp8_row_major = hp_to_fp8_row_major( + y_bf16, + torch.float8_e4m3fn, + LinearMMConfig(), + algo=algo, + ) + + # check scales + assert torch.eq(x_fp8_row_major._scale, y_fp8_row_major._scale) + + # check data + assert torch.all(torch.eq(x_fp8_row_major._data, y_fp8_row_major._data)) + + # check shapes + assert x_fp8_row_major.shape == y_fp8_row_major.shape + + # check strides + assert x_fp8_row_major.stride() == y_fp8_row_major.stride() + + # check memory layout + assert is_row_major(x_fp8_row_major.stride()) + assert is_row_major(y_fp8_row_major.stride()) + + # check underlying memory layout + assert ( + x_fp8_row_major._data.storage().tolist() + == y_fp8_row_major._data.storage().tolist() + ) + + # assert that error is raised when input tensor is not contiguous + with pytest.raises(AssertionError, match="tensor must be contiguous"): + hp_to_fp8_row_major( + y_bf16.t(), # transpose so tensor memory layout is no longer contiguous + torch.float8_e4m3fn, + LinearMMConfig(), + ) + + +@pytest.mark.parametrize( + "algo", + [KernelAlgorithm.REDUCTION, KernelAlgorithm.ATOMIC_MAX], +) +@pytest.mark.parametrize( + "input_shape", + [(2, 4), (32, 16), (512, 512)], +) +def test_fp8_hp_to_fp8_row_major_t(input_shape: tuple[int, int], algo: KernelAlgorithm): + assert torch.cuda.is_available() + device = "cuda" + input_bf16 = torch.tensor( + [[1, 2, 3], [4, 5, 6]], dtype=torch.bfloat16, device=device + ) + x_bf16 = input_bf16.clone().detach().to(device) + y_bf16 = input_bf16.clone().detach().to(device) + + # production implementation + x_fp8_row_major = hp_tensor_to_float8_dynamic( + x_bf16, + torch.float8_e4m3fn, + LinearMMConfig(), + ) + x_fp8_row_major_t = x_fp8_row_major.t().contiguous() + + # float8nocompile triton implementation + y_fp8_row_major_t = hp_to_fp8_row_major_t( + y_bf16, + torch.float8_e4m3fn, + LinearMMConfig(), + algo=algo, + ) + + # check scales + assert torch.eq(x_fp8_row_major_t._scale, y_fp8_row_major_t._scale) + + # check data + assert torch.all(torch.eq(x_fp8_row_major_t._data, y_fp8_row_major_t._data)) + + # check shapes + assert x_fp8_row_major_t.shape == y_fp8_row_major_t.shape + + # check strides + assert x_fp8_row_major_t.stride() == y_fp8_row_major_t.stride() + + # check memory layout + assert is_row_major(x_fp8_row_major_t.stride()) + assert is_row_major(y_fp8_row_major_t.stride()) + + # check underlying memory layout + assert ( + x_fp8_row_major_t._data.storage().tolist() + == y_fp8_row_major_t._data.storage().tolist() + ) + + # assert that error is raised when input tensor is not contiguous + with pytest.raises(AssertionError, match="tensor must be contiguous"): + hp_to_fp8_row_major( + y_bf16.t(), # transpose so tensor memory layout is no longer contiguous + torch.float8_e4m3fn, + LinearMMConfig(), + ) + + +@pytest.mark.parametrize( + "algo", + [KernelAlgorithm.REDUCTION, KernelAlgorithm.ATOMIC_MAX], +) +@pytest.mark.parametrize( + "input_shape", + [(2, 4), (32, 16), (512, 512)], +) +def test_fp8_hp_to_fp8_col_major(input_shape: tuple[int, int], algo: KernelAlgorithm): + assert torch.cuda.is_available() + device = "cuda" + input_bf16 = torch.randn(input_shape, dtype=torch.bfloat16, device=device) + x_bf16 = input_bf16.clone().detach().to(device) + y_bf16 = input_bf16.clone().detach().to(device) + + # production implementation + x_fp8_row_major = hp_tensor_to_float8_dynamic( + x_bf16, + torch.float8_e4m3fn, + LinearMMConfig(), + ) + x_fp8_col_major = x_fp8_row_major.t().contiguous().t() + + # float8nocompile triton implementation + y_fp8_col_major = hp_to_fp8_col_major( + y_bf16, + torch.float8_e4m3fn, + LinearMMConfig(), + algo=algo, + ) + + # check scales + assert torch.eq(x_fp8_col_major._scale, y_fp8_col_major._scale) + + # check data + assert torch.all(torch.eq(x_fp8_col_major._data, y_fp8_col_major._data)) + + # check shapes + assert x_fp8_col_major.shape == y_fp8_col_major.shape + + # check strides + assert x_fp8_col_major.stride() == y_fp8_col_major.stride() + + # check memory layout + assert not is_row_major(x_fp8_col_major.stride()) + assert not is_row_major(y_fp8_col_major.stride()) + + # check underlying memory layout + assert ( + x_fp8_col_major._data.storage().tolist() + == y_fp8_col_major._data.storage().tolist() + ) + + # assert that error is raised when input tensor is not contiguous + with pytest.raises(AssertionError, match="tensor must be contiguous"): + hp_to_fp8_col_major( + y_bf16.t(), # transpose so tensor memory layout is no longer contiguous + torch.float8_e4m3fn, + LinearMMConfig(), + ) + + +@pytest.mark.parametrize( + "algo", + [KernelAlgorithm.REDUCTION, KernelAlgorithm.ATOMIC_MAX], +) +@pytest.mark.parametrize( + "input_shape", + [(2, 4), (32, 16), (512, 512)], +) +def test_fp8_hp_to_fp8_col_major_t(input_shape: tuple[int, int], algo: KernelAlgorithm): + assert torch.cuda.is_available() + device = "cuda" + input_bf16 = torch.randn(input_shape, dtype=torch.bfloat16, device=device) + x_bf16 = input_bf16.clone().detach().to(device) + y_bf16 = input_bf16.clone().detach().to(device) + + # production implementation + x_fp8_row_major = hp_tensor_to_float8_dynamic( + x_bf16, + torch.float8_e4m3fn, + LinearMMConfig(), + ) + x_fp8_col_major_t = x_fp8_row_major.contiguous().t() + + # float8nocompile triton implementation + y_fp8_col_major_t = hp_to_fp8_col_major_t( + y_bf16, + torch.float8_e4m3fn, + LinearMMConfig(), + algo=algo, + ) + + # check scales + assert torch.eq(x_fp8_col_major_t._scale, y_fp8_col_major_t._scale) + + # check data + assert torch.all(torch.eq(x_fp8_col_major_t._data, y_fp8_col_major_t._data)) + + # check shapes + assert x_fp8_col_major_t.shape == y_fp8_col_major_t.shape + + # check strides + assert x_fp8_col_major_t.stride() == y_fp8_col_major_t.stride() + + # check memory layout + assert not is_row_major(x_fp8_col_major_t.stride()) + assert not is_row_major(y_fp8_col_major_t.stride()) + + # check underlying memory layout + assert ( + x_fp8_col_major_t._data.storage().tolist() + == y_fp8_col_major_t._data.storage().tolist() + ) + + # assert that error is raised when input tensor is not contiguous + with pytest.raises(AssertionError, match="tensor must be contiguous"): + hp_to_fp8_col_major( + y_bf16.t(), # transpose so tensor memory layout is no longer contiguous + torch.float8_e4m3fn, + LinearMMConfig(), + ) + + +@pytest.mark.parametrize( + "algo", + [KernelAlgorithm.REDUCTION, KernelAlgorithm.ATOMIC_MAX], +) +@pytest.mark.parametrize( + "input_shape", + [(2, 4), (32, 16), (512, 512)], +) +def test_fp8_hp_to_fp8_row_and_col_major( + input_shape: tuple[int, int], algo: KernelAlgorithm +): + assert torch.cuda.is_available() + device = "cuda" + input_bf16 = torch.randn(input_shape, dtype=torch.bfloat16, device=device) + x_bf16 = input_bf16.clone().detach().to(device) + y_bf16 = input_bf16.clone().detach().to(device) + + # production implementation + x_fp8_row_major = hp_tensor_to_float8_dynamic( + x_bf16, + torch.float8_e4m3fn, + LinearMMConfig(), + ) + x_fp8_col_major = x_fp8_row_major.t().contiguous().t() + + # float8nocompile triton implementation + y_fp8_row_major, y_fp8_col_major = hp_to_fp8_row_and_col_major( + y_bf16, + torch.float8_e4m3fn, + LinearMMConfig(), + algo=algo, + ) + + # check scales + assert torch.eq(x_fp8_row_major._scale, y_fp8_row_major._scale) + assert torch.eq(x_fp8_col_major._scale, y_fp8_col_major._scale) + + # check data + assert torch.all(torch.eq(x_fp8_row_major._data, y_fp8_row_major._data)) + assert torch.all(torch.eq(x_fp8_col_major._data, y_fp8_col_major._data)) + + # check shapes + assert x_fp8_row_major.shape == y_fp8_row_major.shape + assert x_fp8_col_major.shape == y_fp8_col_major.shape + + # check strides + assert x_fp8_row_major.stride() == y_fp8_row_major.stride() + assert x_fp8_col_major.stride() == y_fp8_col_major.stride() + + # check memory layout + assert is_row_major(x_fp8_row_major.stride()) + assert is_row_major(y_fp8_row_major.stride()) + assert not is_row_major(x_fp8_col_major.stride()) + assert not is_row_major(y_fp8_col_major.stride()) + + # check underlying memory layout + assert ( + x_fp8_row_major._data.storage().tolist() + == y_fp8_row_major._data.storage().tolist() + ) + assert ( + x_fp8_col_major._data.storage().tolist() + == y_fp8_col_major._data.storage().tolist() + ) + + # assert that error is raised when input tensor is not contiguous + with pytest.raises(AssertionError, match="tensor must be contiguous"): + hp_to_fp8_row_and_col_major( + y_bf16.t(), # transpose so tensor memory layout is no longer contiguous + torch.float8_e4m3fn, + LinearMMConfig(), + ) + + +@pytest.mark.parametrize( + "algo", + [KernelAlgorithm.REDUCTION, KernelAlgorithm.ATOMIC_MAX], +) +@pytest.mark.parametrize( + "input_shape", + [(2, 4), (32, 16), (512, 512)], +) +def test_fp8_hp_to_fp8_row_major_t_and_non_t( + input_shape: tuple[int, int], algo: KernelAlgorithm +): + assert torch.cuda.is_available() + device = "cuda" + input_bf16 = torch.randn(input_shape, dtype=torch.bfloat16, device=device) + x_bf16 = input_bf16.clone().detach().to(device) + y_bf16 = input_bf16.clone().detach().to(device) + + # production implementation + x_fp8_row_major = hp_tensor_to_float8_dynamic( + x_bf16, + torch.float8_e4m3fn, + LinearMMConfig(), + ) + x_fp8_row_major_t = x_fp8_row_major.t().contiguous() + + # float8nocompile triton implementation + y_fp8_row_major, y_fp8_row_major_t = hp_to_fp8_row_major_t_and_non_t( + y_bf16, + torch.float8_e4m3fn, + LinearMMConfig(), + algo=algo, + ) + + # check scales + assert torch.eq(x_fp8_row_major._scale, y_fp8_row_major._scale) + assert torch.eq(x_fp8_row_major_t._scale, y_fp8_row_major_t._scale) + + # check data + assert torch.all(torch.eq(x_fp8_row_major._data, y_fp8_row_major._data)) + assert torch.all(torch.eq(x_fp8_row_major_t._data, y_fp8_row_major_t._data)) + + # check shapes + assert x_fp8_row_major.shape == y_fp8_row_major.shape + assert x_fp8_row_major_t.shape == y_fp8_row_major_t.shape + + # check strides + assert x_fp8_row_major.stride() == y_fp8_row_major.stride() + assert x_fp8_row_major_t.stride() == y_fp8_row_major_t.stride() + + # check memory layout + assert is_row_major(x_fp8_row_major.stride()) + assert is_row_major(y_fp8_row_major.stride()) + assert is_row_major(x_fp8_row_major_t.stride()) + assert is_row_major(y_fp8_row_major_t.stride()) + + # check underlying memory layout + assert ( + x_fp8_row_major._data.storage().tolist() + == y_fp8_row_major._data.storage().tolist() + ) + assert ( + x_fp8_row_major_t._data.storage().tolist() + == y_fp8_row_major_t._data.storage().tolist() + ) + + # assert that error is raised when input tensor is not contiguous + with pytest.raises(AssertionError, match="tensor must be contiguous"): + hp_to_fp8_row_major_t_and_non_t( + y_bf16.t(), # transpose so tensor memory layout is no longer contiguous + torch.float8_e4m3fn, + LinearMMConfig(), + ) + + +@pytest.mark.parametrize( + "algo", + [KernelAlgorithm.REDUCTION, KernelAlgorithm.ATOMIC_MAX], +) +@pytest.mark.parametrize( + "input_shape", + [(2, 4), (32, 16), (512, 512)], +) +def test_fp8_hp_to_fp8_col_major_t_and_non_t( + input_shape: tuple[int, int], algo: KernelAlgorithm +): + assert torch.cuda.is_available() + device = "cuda" + input_bf16 = torch.randn(input_shape, dtype=torch.bfloat16, device=device) + x_bf16 = input_bf16.clone().detach().to(device) + y_bf16 = input_bf16.clone().detach().to(device) + + # production implementation + x_fp8_row_major = hp_tensor_to_float8_dynamic( + x_bf16, + torch.float8_e4m3fn, + LinearMMConfig(), + ) + x_fp8_col_major = x_fp8_row_major.t().contiguous().t() + x_fp8_col_major_t = x_fp8_row_major.t() + + # float8nocompile triton implementation + y_fp8_col_major, y_fp8_col_major_t = hp_to_fp8_col_major_t_and_non_t( + y_bf16, + torch.float8_e4m3fn, + LinearMMConfig(), + algo=algo, + ) + + # check scales + assert torch.eq(x_fp8_col_major._scale, y_fp8_col_major._scale) + assert torch.eq(x_fp8_col_major_t._scale, y_fp8_col_major_t._scale) + + # check data + assert torch.all(torch.eq(x_fp8_col_major._data, y_fp8_col_major._data)) + assert torch.all(torch.eq(x_fp8_col_major_t._data, y_fp8_col_major_t._data)) + + # check shapes + assert x_fp8_col_major.shape == y_fp8_col_major.shape + assert x_fp8_col_major_t.shape == y_fp8_col_major_t.shape + + # check strides + assert x_fp8_col_major.stride() == y_fp8_col_major.stride() + assert x_fp8_col_major_t.stride() == y_fp8_col_major_t.stride() + + # check memory layout + assert not is_row_major(x_fp8_col_major.stride()) + assert not is_row_major(y_fp8_col_major.stride()) + assert not is_row_major(x_fp8_col_major_t.stride()) + assert not is_row_major(y_fp8_col_major_t.stride()) + + # check underlying memory layout + assert ( + x_fp8_col_major._data.storage().tolist() + == y_fp8_col_major._data.storage().tolist() + ) + assert ( + x_fp8_col_major_t._data.storage().tolist() + == y_fp8_col_major_t._data.storage().tolist() + ) + + # assert that error is raised when input tensor is not contiguous + with pytest.raises(AssertionError, match="tensor must be contiguous"): + hp_to_fp8_col_major_t_and_non_t( + y_bf16.t(), # transpose so tensor memory layout is no longer contiguous + torch.float8_e4m3fn, + LinearMMConfig(), + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/ep/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/ep/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d655719dd5f3b45941b592bd3b9ec930595f1071 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/ep/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/ep/__pycache__/a2a_combine.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/ep/__pycache__/a2a_combine.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..773521a808f5c27edb249cac440840a3a794ccd2 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/ep/__pycache__/a2a_combine.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/ep/__pycache__/a2a_dispatch.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/ep/__pycache__/a2a_dispatch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b11104c5364b1ef87387be0cd2ce1bfa252de43 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/ep/__pycache__/a2a_dispatch.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/ep/__pycache__/kernels.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/ep/__pycache__/kernels.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1c5f995c1b5af451a97be91fd7506b41b1c7d44 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/ep/__pycache__/kernels.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/ep/__pycache__/permute.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/ep/__pycache__/permute.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..982e458bc158ac2dbbd037af4650d743a0de0c8e Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/ep/__pycache__/permute.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/ep/__pycache__/unpermute.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/ep/__pycache__/unpermute.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2de08a57a0413bf09620d3304fafe15bdebfb145 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/ep/__pycache__/unpermute.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/kernels/mxfp8/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/kernels/mxfp8/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..171b741944e4b3178cd03f58c3b64ca1d081c741 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/kernels/mxfp8/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/kernels/mxfp8/__pycache__/comms.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/kernels/mxfp8/__pycache__/comms.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eea1243893d97830b7eed9607e9ff8206f62c709 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/kernels/mxfp8/__pycache__/comms.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/kernels/mxfp8/__pycache__/cute_utils.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/kernels/mxfp8/__pycache__/cute_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b901067205a4e2fe947618fd3b53c3655c2bb58 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/kernels/mxfp8/__pycache__/cute_utils.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/kernels/mxfp8/__pycache__/cutedsl_quantize_2d.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/kernels/mxfp8/__pycache__/cutedsl_quantize_2d.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c296d9c973740a4a6ba39d9b9b18fe61c49a32b6 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/kernels/mxfp8/__pycache__/cutedsl_quantize_2d.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/kernels/mxfp8/__pycache__/cutedsl_quantize_3d.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/kernels/mxfp8/__pycache__/cutedsl_quantize_3d.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e794f81240cdccbc283907436386d511cf1afc5 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/kernels/mxfp8/__pycache__/cutedsl_quantize_3d.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/kernels/mxfp8/__pycache__/quant.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/kernels/mxfp8/__pycache__/quant.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16ca839116073ac15a014407776acfbe0565b081 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/kernels/mxfp8/__pycache__/quant.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..190e8b046232a20447ed1af574b4fa2ba1baf832 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/__pycache__/quant_api.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/__pycache__/quant_api.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3450330903e8e60bb678705fd1312253a8b0f121 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/__pycache__/quant_api.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3fba2beedd30c6749278e6a37313998979e48bd9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook/__init__.py @@ -0,0 +1,14 @@ +from .codebook_ops import ( + choose_qparams_codebook, + dequantize_codebook, + quantize_codebook, +) +from .codebook_quantized_tensor import CodebookQuantizedTensor, codebook_weight_only + +__all__ = [ + "CodebookQuantizedTensor", + "codebook_weight_only", + "quantize_codebook", + "dequantize_codebook", + "choose_qparams_codebook", +] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook/codebook_ops.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook/codebook_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..201dc30f2758c30fa1d48be58e586541f86bd405 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook/codebook_ops.py @@ -0,0 +1,445 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. +from typing import List, Optional, Tuple + +import torch + +from torchao.quantization.quant_primitives import ( + _DTYPE_TO_QVALUE_BOUNDS, + _SUB_BYTE_UINT_BOUNDS, +) + + +def quantize_codebook( + input: torch.Tensor, + codebook: torch.Tensor, + scales: torch.Tensor, + chunk_size: int = 1024, + code_dtype: torch.dtype = torch.uint4, +) -> torch.Tensor: + """ + code modified from: https://github.com/Vahe1994/AQLM/blob/main/src/kmeans.py + + Args: + input (torch.Tensor): Input tensor to quantize, shape (d1, d2, ..., dN). + codebook (torch.Tensor): Codebook tensor for quantization, shape (k, b1, b2, ..., bN) where b_i are block sizes. + scales (torch.Tensor): Scales, shape (d1, d2, ..., dN // scale_block_size, 1). + chunk_size (int): Number of elements to process per chunk to control memory usage. + code_dtype (torch.dtype): dtype for the codes. + + Output: + codes (torch.Tensor): indices of the closest codebook entries for each block, shape (d1//b1, d2//b2, ..., dN//bN). + """ + if code_dtype in _SUB_BYTE_UINT_BOUNDS: + code_dtype = torch.uint8 + assert input.dtype in [ + torch.float32, + torch.float16, + torch.bfloat16, + ], f"Unsupported input dtype: {input.dtype}" + assert codebook.dim() == input.dim() + 1, ( + f"codebook dim ({codebook.dim()}) must be input dim + 1 ({input.dim() + 1})" + ) + + k = codebook.shape[0] + block_size = codebook.shape[1:] + input_size = input.shape + D = input.dim() + for i in range(D): + assert (input_size[i] % block_size[i]) == 0, ( + f"dimension {i} of input ({input_size[i]}) must be divisible by block_size ({block_size[i]})." + ) + + num_scale_blocks = scales.shape[-2] + + new_shape = input_size[:-1] + (num_scale_blocks, -1) + input_reshaped = input.view( + *new_shape + ) # shape: (d1, d2, ..., num_scale_blocks, scale_block_size) + input_reshaped = input_reshaped / scales + + input = input_reshaped.view(*input_size) + input_flat = _reshape_into_blocks( + input, block_size + ) # shape: (num_blocks, block_vector_size) + + codebook_flat = codebook.reshape(k, -1) + + codes = torch.empty(input_flat.size(0), dtype=torch.int64, device=input.device) + + # Process in chunks to avoid memory spikes + for chunk_start in range(0, input_flat.size(0), chunk_size): + chunk_end = min(chunk_start + chunk_size, input_flat.size(0)) + + input_chunk = input_flat[chunk_start:chunk_end] + input_chunk = input_chunk + + # Compute distances and find nearest codebook entries for the chunk + distances = torch.addmm( + torch.bmm(codebook_flat[:, None, :], codebook_flat[:, :, None]).flatten(), + input_chunk, + codebook_flat.T, + beta=-0.5, + ) + # distance = || input_chunk[:, None, :] - codebook_flat[None, :, :] ||^2 = || input_chunk ||^2 + || codebook_flat ||^2 - 2 * input_chunk @ codebook_flat.T + # don't need to compute input_chunk squared norm as it's constant during argmax + + codes[chunk_start:chunk_end] = distances.argmax(dim=1) + + block_grid_shape = [input_size[i] // block_size[i] for i in range(D)] + codes = codes.view(*block_grid_shape) # shape: (d1//b1, d2//b2, ..., dN//bN) + + return codes.to(code_dtype) + + +def dequantize_codebook( + codes: torch.Tensor, + codebook: torch.Tensor, + scales: torch.Tensor, + output_dtype: torch.dtype = torch.float32, +) -> torch.Tensor: + """ + Reconstructs the original tensor from codes and the codebook. + + Args: + codes (torch.Tensor): Indices of codebook entries for each block, + shape (d1//b1, d2//b2, ..., dN//bN). + codebook (torch.Tensor): Codebook tensor used for quantization, + shape (k, b1, b2, ..., bN) where b_i are block sizes. + scales (torch.Tensor): Scales, shape (d1, d2, ..., dN // scale_block_size, 1). + output_dtype (torch.dtype): dtype for the output tensor. + + Returns: + dequant (torch.Tensor): Reconstructed tensor, shape (out_features, in_features) + """ + assert output_dtype in [ + torch.float32, + torch.float16, + torch.bfloat16, + ], f"Unsupported output dtype: {output_dtype}" + + block_size = codebook.shape[1:] + block_grid_shape = codes.shape + D = codebook.dim() - 1 + original_shape = [block_grid_shape[i] * block_size[i] for i in range(D)] + + # Use codes to lookup corresponding codebook entries and reshape + dequant = codebook[codes] # shape: (*block_grid_shape, *block_size) + + # probably can make this simpler + dequant = _reshape_from_blocks( + dequant.view(-1, int(torch.prod(torch.tensor(block_size)))), + block_size, + tuple(original_shape), + ) + + num_scale_blocks = scales.shape[-2] + + new_shape = dequant.shape[:-1] + (num_scale_blocks, -1) + dequant = dequant.view( + *new_shape + ) # (d1, d2, ..., num_scale_blocks, scale_block_size) + dequant.mul_(scales) + + dequant = dequant.view(*original_shape) + + return dequant.to(output_dtype) + + +@torch.no_grad() +def choose_qparams_codebook( + input_tensor: torch.Tensor, + block_size: Tuple[int, ...], + scale_block_size: int, + code_dtype: torch.dtype, + max_iter: int = 200, + devices: Optional[List[torch.device]] = None, +) -> torch.Tensor: + """ + Initialize the codebook using k-means clustering on blocks of the input tensor. + + Args: + input_tensor (torch.Tensor): The input tensor to be quantized. + block_size (Tuple[int, ...],): The size of the blocks for k-means clustering. + scale_block_size (int): The size of the blocks that share a scale + code_dtype (torch.dtype): The dtype for the codes. + max_iter (int): Maximum number of k-means iterations. + devices (List[torch.device]): Devices to run k-means on. + + Returns: + torch.Tensor: The codebook tensor, shape (codebook_size, *block_size). + """ + if code_dtype == torch.int32: + codebook_size = 2**16 + else: + codebook_size = _DTYPE_TO_QVALUE_BOUNDS[code_dtype][1] + 1 + + input_size = input_tensor.shape + D = input_tensor.dim() + for i in range(D): + assert input_size[i] % block_size[i] == 0, ( + f"Dimension {i} must be divisible by block_size {block_size[i]}." + ) + + assert input_tensor.shape[-1] % scale_block_size == 0, ( + f"input_features ({input_tensor.shape[-1]}) must be divisible by scale_block_size ({scale_block_size})." + ) + num_scale_blocks = input_tensor.shape[-1] // scale_block_size + + new_shape = list(input_size[:-1]) + [num_scale_blocks, scale_block_size] + input = input_tensor.view(*new_shape) + + # Not sure if I should make scales max only when block_size is (1, 1) + if block_size == (1, 1): + scales = input.max( + dim=(-1), keepdim=True + ).values # Shape: [*input_size[:-1], num_scale_blocks, 1] + else: + scales = torch.linalg.vector_norm( + input, dim=-1, keepdim=True + ) # Shape: [*input_size[:-1], num_scale_blocks, 1] + scales = torch.clamp(scales, min=1e-9) + + input = input / scales + + input = input.view(*input_size) + + input = _reshape_into_blocks( + input, block_size + ) # Shape: (num_blocks, block_vector_size) + + codebook, _, _ = fit_kmeans( + input, + k=codebook_size, + max_iter=max_iter, + devices=devices, + ) + + return codebook.view(codebook_size, *block_size), scales + + +@torch.jit.script +def _kmeans_greedy_init(data: torch.Tensor, k: int) -> torch.Tensor: + # code modified from: https://github.com/Vahe1994/AQLM/blob/main/src/kmeans.py not sure if I should modify for + clusters = torch.zeros(k, data.shape[1], device=data.device) + running_min_distances = torch.full( + (data.shape[0],), torch.inf, device=data.device, dtype=data.dtype + ) + data_norm_squared = torch.linalg.vector_norm(data, dim=1).square() + + for i in range(k): + clusters[i] = data[running_min_distances.argmax()] + distances_to_cluster_i = ( + data_norm_squared + - 2 * data @ clusters[i] + + torch.linalg.vector_norm(clusters[i]).square() + ) + running_min_distances = torch.minimum( + running_min_distances, distances_to_cluster_i, out=running_min_distances + ) + return clusters + + +@torch.jit.script +def fit_kmeans( + data: torch.Tensor, + k: int, + max_iter: int = 200, + check_every: int = 10, + rtol: float = 1e-06, + atol: float = 1e-08, + greedy_init: bool = True, + block_size_vals: int = 2**30, + devices: Optional[List[torch.device]] = None, +): + """ + code modified from: https://github.com/Vahe1994/AQLM/blob/main/src/kmeans.py not sure if I should modify for + :param data: [nsamples, dim] + :param k: number of centroids + :param max_iter: run at most this many iterations + :param check_every: check for convergence (allclose(new_centroids, old_centroids)) once in this many steps + :param rtol: early stopping relative tolerance for centroids + :param atol: early stopping absolute tolerance for centroids + :param block_size_vals: how many dot products to compute at a time + :param devices: if specified, run kmeans in data-parallel mode across these devices + :return: (clusters float[k, dim], data_indices int[nsamples], reconstructed_data: float[nsamples, dim]) + """ + if devices is None: + devices = [data.device] + + if greedy_init: + clusters = _kmeans_greedy_init(data, k) + else: + clusters = data[torch.randperm(data.shape[0])[:k], :] # [k, dim] + + block_size = block_size_vals // k + shard_size = (len(data) - 1) // len(devices) + 1 + data = [ + data[gi * shard_size : (gi + 1) * shard_size].to(devices[gi], non_blocking=True) + for gi in range(len(devices)) + ] + nearest_indices = [ + torch.empty(len(data[gi]), dtype=torch.int64, device=devices[gi]) + for gi in range(len(devices)) + ] + clusters = [clusters.to(device, non_blocking=True) for device in devices] + + for i in range(max_iter): + for block_start in range(0, shard_size, block_size): + for gi in range(len(devices)): + nearest_indices[gi][block_start : block_start + block_size] = ( + torch.addmm( + torch.bmm( + clusters[gi][:, None, :], clusters[gi][:, :, None] + ).flatten(), + data[gi][block_start : block_start + block_size], + clusters[gi].T, + beta=-0.5, + ).argmax(1) + ) + # note: the above formula equals to - 0.5 || data[:, None, :] - clusters[None, :, :] || ^ 2 + const + + if len(devices) == 1: + new_clusters = [ + clusters[0] + .clone() + .index_reduce_( + dim=0, + index=nearest_indices[0], + source=data[0], + reduce="mean", + include_self=False, + ) + ] + else: + cluster_sums = [ + torch.zeros_like(clusters[gi]) + .index_add(dim=0, index=nearest_indices[gi], source=data[gi]) + .to(devices[0], non_blocking=True) + for gi in range(len(devices)) + ] + cluster_counts = [ + torch.bincount(nearest_indices[gi], minlength=k).to( + devices[0], non_blocking=True + ) + for gi in range(len(devices)) + ] + for gi in range(1, len(devices)): + cluster_sums[0] += cluster_sums[gi] + cluster_counts[0] += cluster_counts[gi] + + new_clusters = [ + cluster_sums[0] / cluster_counts[0].unsqueeze(1).clamp_min(1) + ] + new_clusters[0] += (cluster_counts[0].unsqueeze(1) == 0) * clusters[0] + for gi in range(1, len(devices)): + new_clusters.append(new_clusters[0].to(devices[gi], non_blocking=True)) + + if i % check_every == 0: + if torch.allclose(new_clusters[0], clusters[0], rtol=rtol, atol=atol): + break + clusters = new_clusters + for block_start in range(0, shard_size, block_size): + for gi in range(len(devices)): + nearest_indices[gi][block_start : block_start + block_size] = torch.addmm( + torch.bmm(clusters[gi][:, None, :], clusters[gi][:, :, None]).flatten(), + data[gi][block_start : block_start + block_size], + clusters[gi].T, + beta=-0.5, + ).argmax(1) + + clusters = clusters[0] + nearest_indices = torch.cat( + [nearest_indices[gi].to(devices[0]) for gi in range(len(devices))], dim=0 + ) + reconstructed_data = clusters[nearest_indices] + return clusters, nearest_indices, reconstructed_data + + +def _reshape_into_blocks( + input: torch.Tensor, block_size: Tuple[int, ...] +) -> torch.Tensor: + """ + Reshape an N-D input tensor into a 2D tensor where each row corresponds to one block. + """ + assert len(block_size) == input.dim(), ( + f"block_size {block_size} must match the input dimension {input.dim()}" + ) + input_size = input.shape + + # Create shape with alternating (num_blocks_along_dim, block_size_dim) + reshaped_dims = [] + for i in range(input.dim()): + assert input_size[i] % block_size[i] == 0, ( + f"Input size at dim {i} ({input_size[i]}) must be divisible by block_size[i] ({block_size[i]})." + ) + reshaped_dims.extend([input_size[i] // block_size[i], block_size[i]]) + + input_reshaped = input.view(*reshaped_dims) # Shape: [g1, b1, g2, b2, ..., gD, bD] + + D = input.dim() + perm_order = list(range(2 * D)) + grid_dims = perm_order[0::2] + block_dims = perm_order[1::2] + perm_order = grid_dims + block_dims + + input_reshaped = input_reshaped.permute( + *perm_order + ) # Shape: [g1, g2, ..., gD, b1, b2, ..., bD] + + num_blocks = 1 + for i in range(D): + num_blocks *= input_size[i] // block_size[i] + block_vector_size = 1 + for b in block_size: + block_vector_size *= b + + input_flat = input_reshaped.reshape(num_blocks, block_vector_size) + return input_flat + + +def _reshape_from_blocks( + blocks: torch.Tensor, block_size: Tuple[int, ...], original_shape: Tuple[int, ...] +) -> torch.Tensor: + """ + Reshape from the 2D block form (num_blocks, block_vector_size) back to the original N-D shape. + """ + D = len(block_size) + + reshaped_dims = [] + num_blocks = 1 + for i in range(D): + reshaped_dims.extend([original_shape[i] // block_size[i], block_size[i]]) + num_blocks *= original_shape[i] // block_size[i] + block_vector_size = 1 + for b in block_size: + block_vector_size *= b + + perm_order = [] + for i in range(D): + perm_order.append(i * 2) # grid dim indices first + for i in range(D): + perm_order.append(i * 2 + 1) # block dim indices after + + perm_inverse = [0] * (2 * D) + for idx, val in enumerate(perm_order): + perm_inverse[val] = idx + + input_permuted_shape = [] + for i in range(D): + input_permuted_shape.append(original_shape[i] // block_size[i]) + for i in range(D): + input_permuted_shape.append(block_size[i]) + + blocks_permuted = blocks.view( + *input_permuted_shape + ) # Shape: [g1, g2, ..., gD, b1, b2, ..., bD] + + blocks_unpermuted = blocks_permuted.permute( + *perm_inverse + ) # Shape: [g1, b1, g2, b2, ..., gD, bD] + + return blocks_unpermuted.reshape(*original_shape) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook/codebook_quantized_tensor.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook/codebook_quantized_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..424336f2417fdb3c6a1a571e1528f0637879a505 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook/codebook_quantized_tensor.py @@ -0,0 +1,308 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. +from dataclasses import dataclass +from typing import Optional, Tuple + +import torch + +from torchao.core.config import AOBaseConfig +from torchao.prototype.dtypes.uintx.uintx_utils import _DTYPE_TO_BIT_WIDTH, UintxTensor +from torchao.prototype.quantization.codebook.codebook_ops import ( + choose_qparams_codebook, + dequantize_codebook, + quantize_codebook, +) +from torchao.quantization.transform_module import ( + register_quantize_module_handler, +) +from torchao.utils import TorchAOBaseTensor + +aten = torch.ops.aten + + +class CodebookQuantizedTensor(TorchAOBaseTensor): + """ + Codebook quantized tensor subclass. + + Codebook (lookup table) quantization involves partitioning the input tensor into blocks, and replacing each block + with the index of the closest entry in a predefined codebook. + + Fields: + codes (torch.Tensor): Tensor of indices representing blocks in the original tensor. Each index + maps to a corresponding codebook entry. + codebook (torch.Tensor): Tensor representing the quantization codebook, where each entry + corresponds to a block in the original tensor. Shape is `(codebook_size, out_block_size, in_block_size)`. + block_size (Tuple[int, ...]): Granularity of quantization, specifying the dimensions of tensor + blocks that share the same quantization parameters. + shape (torch.Size): Shape of the original high-precision tensor. + dtype (torch.dtype): dtype of the original high-precision tensor. + """ + + @staticmethod + def __new__( + cls, + codes: torch.Tensor, + codebook: torch.Tensor, + block_size: Tuple[int, ...], + scales: torch.Tensor, + shape: torch.Size, + dtype=None, + strides=None, + ): + kwargs = {} + kwargs["device"] = codes.device + kwargs["layout"] = ( + kwargs.get("layout") if kwargs.get("layout", False) else codes.layout + ) + kwargs["dtype"] = dtype + if strides is not None: + kwargs["strides"] = strides + kwargs["requires_grad"] = False + return torch.Tensor._make_wrapper_subclass(cls, shape, **kwargs) # type: ignore[attr-defined] + + def __init__( + self, + codes: torch.Tensor, + codebook: torch.Tensor, + block_size: Tuple[int, ...], + scales: torch.Tensor, + shape: torch.Size, + dtype=None, + strides=None, + ): + self.codes = codes + self.codebook = codebook + self.block_size = block_size + self.scales = scales + self._dtype = dtype # not sure this is right + + def __repr__(self): + return ( + f"{self.__class__.__name__}(codes={self.codes}, codebook={self.codebook}, block_size={self.block_size}, scales={self.scales}, " + f"shape={self.shape}, device={self.device}, dtype={self.dtype}, requires_grad={self.requires_grad})" + ) + + def _quantization_type(self): + return f"shape={self.shape}, block_size={self.block_size}, codebook_size={self.codebook.size(0)}, device={self.device}, code_dtype={self.codes.dtype}" + + def dequantize(self, output_dtype: Optional[torch.dtype] = None) -> torch.Tensor: + if output_dtype is None: + output_dtype = self.dtype + + if isinstance(self.codes, UintxTensor): + codes = self.codes.get_plain() + else: + codes = self.codes + if codes.dtype != torch.int32: + # TODO: Investigate and support not casting to torch.int32 for indexing to improve performance + codes = codes.to(torch.int32) + return dequantize_codebook( + codes, + self.codebook, + self.scales, + output_dtype=output_dtype, + ) + + def __tensor_flatten__(self): + return ["codes", "codebook", "scales"], [ + self.block_size, + self.shape, + self.dtype, + ] + + @classmethod + def __tensor_unflatten__( + cls, tensor_data_dict, tensor_attributes, outer_size, outer_stride + ): + codes = tensor_data_dict["codes"] + codebook = tensor_data_dict["codebook"] + scales = tensor_data_dict["scales"] + block_size, shape, dtype = tensor_attributes + return cls( + codes, + codebook, + block_size, + scales, + shape if outer_size is None else outer_size, + dtype=dtype, + strides=outer_stride, + ) + + @classmethod + def from_float( + cls, + input_tensor: torch.Tensor, + block_size: Tuple[int, ...], + code_dtype: torch.dtype, + scale_block_size: int, + chunk_size: int = 1024, + ): + """ + Creates a CodebookQuantizedTensor from a floating-point tensor by performing codebook quantization. + + Args: + input_tensor (torch.Tensor): The input floating-point tensor to quantize. + block_size (Tuple[int, ...]): The size of the blocks for which codes are assigned. + code_dtype (torch.dtype): The dtype of the codes. + chunk_size (int): The chunk size to use during quantization (to control memory usage). + """ + + codebook, scales = choose_qparams_codebook( + input_tensor.to(torch.float32), block_size, scale_block_size, code_dtype + ) # .to(torch.float32) because I think k_means isn't numerically stable + + codes = quantize_codebook( + input_tensor.to(torch.float32), codebook, scales, chunk_size, code_dtype + ) + if code_dtype in _DTYPE_TO_BIT_WIDTH: + codes = UintxTensor.from_uint8(codes, dtype=code_dtype) + + codebook = codebook.to(input_tensor.dtype) + scales = scales.to(input_tensor.dtype) + + return cls( + codes, + codebook, + block_size, + scales, + input_tensor.shape, + dtype=input_tensor.dtype, + ) + + def to(self, *args, **kwargs): + # I'm not sure if this is right + kwargs = self._get_to_kwargs(*args, **kwargs) + device = kwargs.pop("device") + return self.__class__( + self.codes.to(device), + self.codebook.to(device), + self.block_size, + self.scales.to(device), + self.shape, + **kwargs, + ) + + def _apply_fn_to_data(self, fn): + # Apply function to only codes? + return self.__class__( + fn(self.codes), + self.codebook, + self.block_size, + self.scales, + self.shape, + dtype=self.dtype, + ) + + @classmethod + def __torch_function__(cls, func, types, args=(), kwargs=None): + if kwargs is None: + kwargs = {} + + if func in CODEBOOK_TORCH_FUNCTIONS: + return CODEBOOK_TORCH_FUNCTIONS[func](*args, **kwargs) + + if any(isinstance(arg, cls) for arg in args): + # Dequantize all instances of CodebookQuantizedTensor in args + new_args = tuple( + arg.dequantize() if isinstance(arg, cls) else arg for arg in args + ) + + return func(*new_args, **kwargs) + else: + return NotImplemented + + def detach(self): + """ + Returns a new `CodebookQuantizedTensor`. + """ + return self.__class__( + self.codes.detach(), + self.codebook.detach(), + self.block_size, + self.scales.detach(), + self.shape, + dtype=self.dtype, + ) + + def requires_grad_(self, requires_grad=True): + """ + Modifies the tensor's `requires_grad` status in-place. + """ + self.codes.requires_grad_(requires_grad) + self.codebook.requires_grad_(requires_grad) + self.scales.requires_grad_(requires_grad) + return self + + @property + def dtype(self): + # Hacky way to avoid recursion with __torch_function__ + return self._dtype + + +CODEBOOK_TORCH_FUNCTIONS = {} + + +def implements_torch_function(torch_function): + def decorator(func): + CODEBOOK_TORCH_FUNCTIONS[torch_function] = func + return func + + return decorator + + +@implements_torch_function(torch.Tensor.detach) +def function_detach(tensor, *args, **kwargs): + return tensor.detach() + + +@implements_torch_function(torch.Tensor.requires_grad_) +def function_requires_grad_(tensor, *args, **kwargs): + return tensor.requires_grad_(*args, **kwargs) + + +@dataclass +class CodebookWeightOnlyConfig(AOBaseConfig): + dtype: torch.dtype = torch.uint4 + block_size: Tuple[int, int] = (1, 1) + scale_block_size: int = None + + +# for bc +codebook_weight_only = CodebookWeightOnlyConfig + + +@register_quantize_module_handler(CodebookWeightOnlyConfig) +def _codebook_weight_only_transform( + module: torch.nn.Module, + config: CodebookWeightOnlyConfig, +): + """ + Applies codebook weight-only quantization to linear layers. + + Args: + dtype: torch.uint1 to torch.uint8, torch.int32 supported. + block_size: Tuple of (out_features, in_features) to control quantization granularity. + scale_block_size (int): The size of the blocks that share a scale + Returns: + Callable for quantization transformation. + """ + dtype = config.dtype + block_size = config.block_size + scale_block_size = config.scale_block_size + weight = module.weight + + if weight.numel() > 2**27: + return module # k_means is too numerically unstable + if scale_block_size is None: + scale_block_size = weight.shape[1] + quantized_weight = CodebookQuantizedTensor.from_float( + weight, + block_size=block_size, + code_dtype=dtype, + scale_block_size=scale_block_size, + ) + module.weight = torch.nn.Parameter(quantized_weight, requires_grad=False) + return module diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook_coreml/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook_coreml/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d0da8fcaf1de5785d84a8d6e5f4afaac09498022 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook_coreml/__init__.py @@ -0,0 +1,13 @@ +from .api import CodebookWeightOnlyConfig +from .codebook_ops import ( + choose_qparams_and_quantize_codebook_coreml, + dequantize_codebook, +) +from .codebook_quantized_tensor import CodebookQuantizedTensor + +__all__ = [ + "CodebookQuantizedTensor", + "CodebookWeightOnlyConfig", + "choose_qparams_and_quantize_codebook_coreml", + "dequantize_codebook", +] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook_coreml/api.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook_coreml/api.py new file mode 100644 index 0000000000000000000000000000000000000000..36fa0d299f756fbb7aced8e43cff818b24b39395 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook_coreml/api.py @@ -0,0 +1,53 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +from dataclasses import dataclass +from typing import List + +import torch + +from torchao.core.config import AOBaseConfig +from torchao.prototype.quantization.codebook_coreml.codebook_quantized_tensor import ( + CodebookQuantizedTensor, +) +from torchao.quantization.transform_module import ( + register_quantize_module_handler, +) +from torchao.utils import is_package_at_least + + +@dataclass +class CodebookWeightOnlyConfig(AOBaseConfig): + dtype: torch.dtype + block_size: List[int] + + +@register_quantize_module_handler(CodebookWeightOnlyConfig) +def _codebook_weight_only_transform( + module: torch.nn.Module, + config: CodebookWeightOnlyConfig, +): + """ + Applies codebook weight-only quantization to linear layers. + + Args: + dtype: torch.uint1 to torch.uint8, torch.int32 supported. + Returns: + Callable for quantization transformation. + """ + if not is_package_at_least("coremltools", "8.3.0"): + raise ImportError("Requires coremltools >= 8.3.0") + + dtype = config.dtype + weight = module.weight + + quantized_weight = CodebookQuantizedTensor.from_float( + weight, + dtype, + config.block_size, + ) + module.weight = torch.nn.Parameter(quantized_weight, requires_grad=False) + return module diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook_coreml/codebook_ops.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook_coreml/codebook_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..c5f56c9d622a609e573c877d72a832c5d3fccaef --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook_coreml/codebook_ops.py @@ -0,0 +1,235 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. +from typing import List, Optional, Tuple + +import torch + +from torchao.quantization.quant_primitives import ( + _DTYPE_TO_BIT_WIDTH, + _SUB_BYTE_UINT_BOUNDS, +) +from torchao.utils import _register_custom_op + +quant_lib = torch.library.Library("quant", "FRAGMENT") +register_custom_op = _register_custom_op(quant_lib) + + +# wrapper around coreml util: https://github.com/apple/coremltools/blob/1c0e5cb1c1e3ab759af107b54f2be18b7c03f8aa/coremltools/models/neural_network/quantization_utils.py#L363 +@torch.no_grad +@register_custom_op +def choose_qparams_and_quantize_codebook_coreml( + input_tensor: torch.Tensor, + code_dtype: torch.dtype, + block_size: List[int], + force_kmeans1d: bool = False, + cluster_dim: int = 1, + vector_axis: Optional[int] = None, +) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Initialize the codebook using k-means clustering on blocks of the input tensor. + + Args: + input_tensor (torch.Tensor): The input tensor to be quantized. + code_dtype (torch.dtype): The dtype for the codes. [torch.uint1, ..., torch.uint8] + block_size (List[int]): block sizes for how many elements in each dimension share + the same lookup table (len(block_size) == input_tensor.dim()) + Each dimension of input_tensor must be divisible by the corresponding element of block_size + Look up tables are indexed by {(di // bi) for i in input_tensor.dim()} + For example, if the input tensor has shape (N, K), and block_size is (N, group_size), this means + there is a lookup table for group_size columns, i.e., (K // group_size) total look up tables + force_kmeans1d (bool): Use kmeans1d regardless of number of weights + cluster_dim (int): this means the size of the vector for vector lookup table quantization + e.g. when cluster_dim is 4, instead of quantizing each scalar value one by one, we quantize + the tensor in a unit of 4 element vectors, a vector of original tensor will be mapped to + a vector in the codebook (lookup table) based on the indices. + vector_axis (Optional[int]): used in vector quantization, see more docs in https://github.com/apple/coremltools/blob/1c0e5cb1c1e3ab759af107b54f2be18b7c03f8aa/coremltools/optimize/_utils.py#L371 + + Returns: + Tuple[torch.Tensor, torch.Tensor] The codebook (lookup table) Tensor and the quantized Tensor (codes, torch.uint8) + The LUT table has dimension (g0, .., g(N-1), 2**nbits, vec_dim), where: + * The first N dimensions index over the different tables (gi = input_tensor.shape[i] // block_size[i] in each dimension) + * The N + 1 dimension indexes over the nbit indices (2 ** nbits) + * The N + 2 dimension indexes over the look up values (shape = 1 for scalar) + """ + assert code_dtype in list(_SUB_BYTE_UINT_BOUNDS.keys()) + [torch.uint8] + nbits = _DTYPE_TO_BIT_WIDTH[code_dtype] + assert nbits >= 1 and nbits <= 8, f"nbits must be in [1, 8], got {nbits}" + assert input_tensor.dim() == 2, "Currently only rank 2 tensors are supported" + assert cluster_dim == 1, ( + f"only cluster_dim == 1 is supported right now, got {cluster_dim}" + ) + + original_shape = input_tensor.shape + N, K = original_shape + input_tensor = input_tensor.detach() + + # --- Process block_size --- + assert len(block_size) == 2 + processed_block_size = block_size.copy() + if processed_block_size[0] == -1: + processed_block_size[0] = N + if processed_block_size[1] == -1: + processed_block_size[1] = K + + row_block_size, col_block_size = processed_block_size + assert N % row_block_size == 0, ( + f"Tensor rows ({N}) not divisible by row block size ({row_block_size})" + ) + assert K % col_block_size == 0, ( + f"Tensor cols ({K}) not divisible by col block size ({col_block_size})" + ) + + # --- Determine and execute grouping strategy --- + assert row_block_size == N or col_block_size == K + is_col_grouping = row_block_size == N + + res_lut_list = [] + from coremltools.models.neural_network.quantization_utils import ( + _get_kmeans_lookup_table_and_weight, + ) + + if is_col_grouping: + # STRATEGY 1: Group by COLUMNS + num_luts = K // col_block_size + reshaped_tensor = input_tensor.reshape(N, num_luts, col_block_size) + res_codes = torch.zeros_like(reshaped_tensor, dtype=torch.uint8) + + for i in range(num_luts): + block_to_quantize = reshaped_tensor[:, i, :] + lut, w = _get_kmeans_lookup_table_and_weight( + nbits, block_to_quantize, force_kmeans1d, cluster_dim, vector_axis + ) + res_lut_list.append(torch.from_numpy(lut)) + res_codes[:, i, :] = torch.from_numpy(w.reshape(N, col_block_size)) + + # Shape to match CoreML spec: (1, num_luts, 2**nbits, 1) + final_luts = torch.stack(res_lut_list, dim=0).reshape(1, num_luts, 2**nbits, 1) + + else: # is_row_grouping + # STRATEGY 2: Group by ROWS + num_luts = N // row_block_size + reshaped_tensor = input_tensor.reshape(num_luts, row_block_size, K) + res_codes = torch.zeros_like(reshaped_tensor, dtype=torch.uint8) + + for i in range(num_luts): + block_to_quantize = reshaped_tensor[i, :, :] + lut, w = _get_kmeans_lookup_table_and_weight( + nbits, block_to_quantize, force_kmeans1d, cluster_dim, vector_axis + ) + res_lut_list.append(torch.from_numpy(lut)) + res_codes[i, :, :] = torch.from_numpy(w.reshape(row_block_size, K)) + + final_luts_stacked = torch.stack( + res_lut_list, dim=0 + ) # Shape: (num_luts, 2**nbits, 1) + + # Reshape to the consistent 4D format + # The shape is (num_row_groups, 1, 2**nbits, 1) + final_luts = final_luts_stacked.reshape(num_luts, 1, 2**nbits, 1) + + # Reshape codes back to the original tensor shape + final_codes = res_codes.reshape(*original_shape) + + return final_luts, final_codes + + +@register_custom_op +def dequantize_codebook( + codes: torch.Tensor, + codebook: torch.Tensor, + nbits: int, + block_size: List[int], + output_dtype: torch.dtype = torch.float32, +) -> torch.Tensor: + """ + Reconstructs the original tensor from codes and the codebook. + + Args: + codes (torch.Tensor): Indices of codebook entries for each element + General shape: (d0, d1, d2, ..., dN) + Simple example shape: (N, K) + codebook (torch.Tensor): Codebook tensor used for quantization + General shape: (d0 // block_size[0], ..., dN // block_size[N], 2**nbits, vec_dim), where vec_dim = 1 for scalar look up values + Simple example shape: (1, group_size, 2 ** nbits, 1) for scalar look up values, with 1 table per group_size columns + nbits: int: number of bits for the quantization + block_size (List[int]): a slice of elements with shape block_size will share the same lookup table. + If block_size[i] == -1, then the entire dimension is used. + output_dtype (torch.dtype): dtype for the output tensor. + + Returns: + dequant (torch.Tensor): Reconstructed tensor, shape (N, K) + + """ + assert output_dtype in [ + torch.float32, + torch.float16, + torch.bfloat16, + ], f"Unsupported output dtype: {output_dtype}" + + assert nbits >= 1 and nbits <= 8, f"nbits must be in [1, 8], got {nbits}" + + assert len(block_size) == codes.dim() + block_size = block_size.copy() + for i in range(len(block_size)): + if block_size[i] == -1: + block_size[i] = codes.shape[i] + assert block_size[i] >= 1 and codes.shape[i] % block_size[i] == 0, ( + "block_size[i] must divide codes.shape[i]" + ) + + assert codebook.dim() == codes.dim() + 2 + codebook_shape = codebook.shape + vec_dim = codebook_shape[-1] + quant_levels = 2**nbits + + # Check that last two dimensions of codebook are [quant_levels, vec_dim] + assert codebook_shape[-2] == quant_levels, "Codebook shape mismatch with nbits" + + # Compute shape of lookup group indices from codes shape and block size + code_shape = codes.shape + ndim = codes.ndim + assert len(block_size) == ndim, "block_size must match dimensionality of codes" + + # Compute which codebook slice to use for each element + group_indices = [] + for i in range(ndim): + assert block_size[i] >= 1 and code_shape[i] % block_size[i] == 0, ( + f"dimension {code_shape[i]} not divisible by block size {block_size[i]}" + ) + + # Index of block + idx = ( + torch.arange(code_shape[i], device=codes.device) // block_size[i] + ) # shape (di,) + + # Reshape idx to broadcast along all other dims + shape = [1] * ndim + shape[i] = code_shape[i] + idx = idx.view(*shape) # shape (1, ..., 1, di, 1, ..., 1) + idx = idx.expand(code_shape) # shape (d0, ..., dN) + group_indices.append(idx) + + # Stack the broadcasted group indices + # group_index_tensor at (i0, i1, ..., iN) is the gives the group indices (g0, ..., gN) + # for the element at (i0, i1, ..., iN) in the original code + # If code.shape = (d1, d2, d3), then group_index_tensor.shape = (d1, d2, d3, 3) + group_index_tensor = torch.stack( + group_indices, dim=-1 + ) # shape (d0, d1, ..., dN, ndim) + + # Flatten everything to index efficiently + flat_codes = codes.reshape(-1) # shape (numel,) + flat_groups = group_index_tensor.reshape(-1, ndim) # (numel, ndim) + + # Compute dequantized values via indexing + # index into codebook with (*group_index, code_index, :) + gathered = codebook[(*flat_groups.T, flat_codes)] # shape (numel, vec_dim) + dequant = gathered.reshape(*code_shape, vec_dim) + + if vec_dim == 1: + dequant = dequant.squeeze(-1) + + return dequant.to(dtype=output_dtype) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook_coreml/codebook_quantized_tensor.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook_coreml/codebook_quantized_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..25292c6f16afd7b1569c8a66ede42ad70df838c0 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook_coreml/codebook_quantized_tensor.py @@ -0,0 +1,205 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. +from typing import List, Optional + +import torch +from torch.utils._python_dispatch import return_and_correct_aliasing + +from torchao.prototype.quantization.codebook_coreml.codebook_ops import ( + choose_qparams_and_quantize_codebook_coreml, + dequantize_codebook, +) +from torchao.quantization.quant_primitives import ( + _DTYPE_TO_BIT_WIDTH, +) +from torchao.utils import TorchAOBaseTensor + +aten = torch.ops.aten + + +class CodebookQuantizedTensor(TorchAOBaseTensor): + """ + Codebook quantized tensor subclass. + + Codebook (lookup table) quantization involves partitioning the input tensor into blocks, and replacing each block + with the index of the closest entry in a predefined codebook. + + Fields: + codes (torch.Tensor): Tensor of indices representing blocks in the original tensor. Each index + maps to a corresponding codebook entry, torch.uint8 dtype. + codebook (torch.Tensor): Tensor representing the quantization codebook, where each entry + corresponds to a block in the original tensor. Shape is `(codebook_size, out_block_size, in_block_size)`. + code_dtype (torch.dtype): The logical dtype for the codes, [torch.uint1, ..., torch.uint8] + Note that codes is stored in torch.uint8, this is just addtional information for dequantize op + block_size (Tuple[int, ...]): Granularity of quantization, specifying the dimensions of tensor + blocks that share the same quantization parameters. + shape (torch.Size): Shape of the original high-precision tensor. + dtype (torch.dtype): dtype of the original high-precision tensor. + """ + + tensor_data_attrs = ["codes", "codebook"] + tensor_attributes = ["code_dtype", "block_size", "shape", "dtype"] + + @staticmethod + def __new__( + cls, + codes: torch.Tensor, + codebook: torch.Tensor, + code_dtype: torch.dtype, + block_size: List[int], + shape: torch.Size, + dtype=None, + ): + kwargs = {} + kwargs["device"] = codes.device + kwargs["layout"] = ( + kwargs.get("layout") if kwargs.get("layout", False) else codes.layout + ) + kwargs["dtype"] = dtype + kwargs["requires_grad"] = False + return torch.Tensor._make_wrapper_subclass(cls, shape, **kwargs) # type: ignore[attr-defined] + + def __init__( + self, + codes: torch.Tensor, + codebook: torch.Tensor, + code_dtype: torch.dtype, + block_size: List[int], + shape: torch.Size, + dtype=None, + ): + self.codes = codes + self.codebook = codebook + self.code_dtype = code_dtype + self.block_size = block_size + + def __repr__(self): + return ( + f"{self.__class__.__name__}(codes={self.codes}, codebook={self.codebook}, code_dtype={self.code_dtype}, block_size={self.block_size} " + f"shape={self.shape}, device={self.device}, dtype={self.dtype}, requires_grad={self.requires_grad})" + ) + + def _quantization_type(self): + return f"shape={self.shape}, codebook_shape={self.codebook.shape}, code_dtype={self.code_dtype}, block_size={self.block_size}, device={self.device}" + + def dequantize(self, output_dtype: Optional[torch.dtype] = None) -> torch.Tensor: + if output_dtype is None: + output_dtype = self.dtype + + codes = self.codes + if codes.dtype != torch.int32: + # TODO: Investigate and support not casting to torch.int32 for indexing to improve performance + codes = codes.to(torch.int32) + + # Note: code_dtype is just for lowering pass to understand the range of values in codes + return dequantize_codebook( + codes, + self.codebook, + _DTYPE_TO_BIT_WIDTH[self.code_dtype], + self.block_size, + output_dtype=output_dtype, + ) + + def __tensor_flatten__(self): + return self.tensor_data_attrs, [ + getattr(self, attr) for attr in self.tensor_attributes + ] + + @classmethod + def __tensor_unflatten__( + cls, tensor_data_dict, tensor_attributes, outer_size, outer_stride + ): + return cls( + *[tensor_data_dict[name] for name in cls.tensor_data_attrs], + *tensor_attributes, + ) + + def _apply_fn_to_data(self, fn): + return self.__class__( + *[fn(getattr(self, attr)) for attr in self.tensor_data_attrs], + *[getattr(self, attr) for attr in self.tensor_attributes], + ) + + @classmethod + def from_float( + cls, + input_tensor: torch.Tensor, + code_dtype: torch.dtype, + block_size: List[int], + ): + """ + Creates a CodebookQuantizedTensor from a floating-point tensor by performing codebook quantization. + + Args: + input_tensor (torch.Tensor): The input floating-point tensor to quantize. + code_dtype (torch.dtype): The dtype of the codes, Note the codes Tensor is stored in uint8 + chunk_size (int): The chunk size to use during quantization (to control memory usage). + """ + codebook, codes = choose_qparams_and_quantize_codebook_coreml( + input_tensor, code_dtype, block_size + ) + + assert codes.dtype == torch.uint8, "Only support using uint8 for codes for now" + + return cls( + codes, + codebook, + code_dtype, + block_size, + input_tensor.shape, + dtype=input_tensor.dtype, + ) + + def to(self, *args, **kwargs): + kwargs = self._get_to_kwargs(*args, **kwargs) + device = kwargs.pop("device") + return self.__class__( + *[getattr(self, attr).to(device) for attr in self.tensor_data_attrs], + *[getattr(self, attr) for attr in self.tensor_attributes], + **kwargs, + ) + + +implements = CodebookQuantizedTensor.implements +implements_torch_function = CodebookQuantizedTensor.implements_torch_function + + +@implements([aten.linear.default]) +@implements_torch_function([torch.nn.functional.linear]) +def _(func, types, args, kwargs): + input_tensor, weight_tensor, bias = ( + args[0], + args[1], + args[2] if len(args) > 2 else None, + ) + weight_tensor = weight_tensor.dequantize() + return func(input_tensor, weight_tensor, bias) + + +@implements([aten.embedding.default]) +@implements_torch_function([torch.nn.functional.embedding]) +def _(func, types, args, kwargs): + assert len(args) == 2 + indices, weight_tensor = ( + args[0], + args[1], + ) + weight_tensor = weight_tensor.dequantize() + return func(indices, weight_tensor, **kwargs) + + +@implements([aten.detach.default, aten.alias.default]) +def _(func, types, args, kwargs): + return return_and_correct_aliasing( + func, args, kwargs, args[0]._apply_fn_to_data(torch.detach) + ) + + +@implements(aten.clone.default) +def _(func, types, args, kwargs): + return return_and_correct_aliasing( + func, args, kwargs, args[0]._apply_fn_to_data(torch.clone) + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook_groupwise/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook_groupwise/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8cf56240cd799a7952a059ca0df3fa8b3ec836a1 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook_groupwise/__init__.py @@ -0,0 +1,9 @@ +from .api import GroupwiseLutWeightConfig +from .codebook_quantized_tensor import CodebookQuantizedPackedTensor + +__all__ = [ + "CodebookQuantizedPackedTensor", + "GroupwiseLutWeightConfig", + "QuantizedLutEmbedding", + "EmbeddingLutQuantizer", +] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook_groupwise/api.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook_groupwise/api.py new file mode 100644 index 0000000000000000000000000000000000000000..ff8f17b4d7e4533429172d02a39efb7b903575f2 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook_groupwise/api.py @@ -0,0 +1,146 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. +import types +from dataclasses import dataclass, field +from typing import List, Optional + +import torch + +from torchao.core.config import AOBaseConfig +from torchao.prototype.quantization.codebook_coreml.codebook_quantized_tensor import ( + CodebookQuantizedTensor, +) +from torchao.prototype.quantization.codebook_groupwise.codebook_quantized_tensor import ( + CodebookQuantizedPackedTensor, +) +from torchao.quantization.transform_module import register_quantize_module_handler + + +def _get_linear_extra_repr_for_lut(self) -> str: + """ + Custom __repr__ for a linear module quantized with GroupwiseLutQuantizedTensor. + """ + out_features, in_features = self.weight.shape + + # Access metadata from the custom tensor + bit_width = self.weight.bit_width + lut_group_size = self.weight.lut_group_size + scale_group_size = self.weight.scale_group_size + + # The original bias is fused into the packed weight, so self.bias is None. + has_bias = self.bias is not None + + return ( + f"in_features={in_features}, out_features={out_features}, bias={has_bias}, " + f"quant=GroupwiseLut(bit_width={bit_width}, lut_gs={lut_group_size}, " + f"scale_gs={scale_group_size}')" + ) + + +@dataclass +class GroupwiseLutWeightConfig(AOBaseConfig): + """ + The primary configuration for groupwise Look-Up Table (LUT) quantization. + + This config uses a `block_shape` to define the quantization strategy, + allowing for flexible grouping by either rows or columns. + + Args: + code_dtype (torch.dtype): The target logical dtype for the LUT indices + (e.g., torch.uint4, torch.int4). This determines the codebook size. + weight_dtype (torch.dtype): The target dtype for the raw weight (e.g., torch.float32). + + lut_block_shape (List[int]): Defines the grouping for the look-up table. + This is the key parameter for controlling quantization granularity. + - To group by N rows: use `[N, -1]`. Example: `[2, -1]` means + every 2 rows share a single LUT. + - To group by K columns: use `[-1, K]`. Example: `[-1, 64]` means + every 64 columns share a single LUT. + + scale_block_shape (Optional[List[int]]): Defines grouping for scale factors, + used only by the 'scale' backend. If provided, the 'scale' backend + is automatically selected. The same `[N, -1]` or `[-1, K]` pattern applies. + has_scale (bool): Whether to use scale factors. Defaults to False. + target (str): The backend target for the C++ kernel (e.g., "auto", "aten"). + """ + + # --- Attributes --- + code_dtype: torch.dtype = torch.int4 + weight_dtype: torch.dtype = torch.float32 + backend: str = "auto" + + lut_block_shape: List[int] = field(default_factory=lambda: [2, -1]) + + scale_block_shape: Optional[List[int]] = None + + use_qdq_reference: bool = False + target: Optional[str] = None + cache_dir: Optional[str] = None + has_scale: bool = False + + def __post_init__(self): + """Validate the configuration after initialization.""" + # 1. Validate backend string + if self.backend not in ["auto", "scale", "coreml"]: + raise ValueError(f"Invalid backend: {self.backend}") + + # 2. Validate lut_block_shape + if not ( + isinstance(self.lut_block_shape, list) and len(self.lut_block_shape) == 2 + ): + raise ValueError( + "`lut_block_shape` must be a list of length 2 (e.g., [N, -1] or [-1, K])." + ) + if self.lut_block_shape.count(-1) != 1: + raise ValueError( + "`lut_block_shape` must contain exactly one '-1' to specify the grouping dimension." + ) + if self.has_scale == True: + raise ValueError("currently only support lut quantization without scale") + + # 3. Validate scale_block_shape if it exists + if self.has_scale and self.scale_block_shape is not None: + if not ( + isinstance(self.scale_block_shape, list) + and len(self.scale_block_shape) == 2 + ): + raise ValueError( + "`scale_block_shape` must be a list of length 2 if provided." + ) + + +@register_quantize_module_handler(GroupwiseLutWeightConfig) +def _groupwise_lut_weight_transform( + module: torch.nn.Module, config: GroupwiseLutWeightConfig +) -> torch.nn.Module: + """ + Transforms a linear module by applying groupwise LUT-based weight quantization. + Automatically caches results if config.cache_dir is set, using a hash of + the weight tensor for a unique key. + """ + assert isinstance(module, torch.nn.Linear), ( + "This transform only applies to torch.nn.Linear modules." + ) + weight = module.weight.data + + quantized_tensor = CodebookQuantizedTensor.from_float( + weight, code_dtype=config.code_dtype, block_size=config.lut_block_shape + ) + + if not config.use_qdq_reference: + packed_weight = CodebookQuantizedPackedTensor.from_codebook_quantized_tensor( + tensor=quantized_tensor, bias=module.bias + ) + module.weight = torch.nn.Parameter(packed_weight, requires_grad=False) + if module.bias is not None: + module.bias = None + module.extra_repr = types.MethodType(_get_linear_extra_repr_for_lut, module) + + else: # For reference, dequantize back to float + dequantized_weight = quantized_tensor.dequantize(config.weight_dtype) + module.weight.data.copy_(dequantized_weight) + + return module diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook_groupwise/codebook_quantized_tensor.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook_groupwise/codebook_quantized_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..08afef43c0c86a05fa616454e7603db5da54656e --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook_groupwise/codebook_quantized_tensor.py @@ -0,0 +1,215 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from typing import List, Optional + +import torch +import torch.nn.functional as F +from torch.utils._python_dispatch import return_and_correct_aliasing + +from torchao.prototype.quantization.codebook_coreml.codebook_quantized_tensor import ( + CodebookQuantizedTensor, +) +from torchao.prototype.quantization.codebook_utils.codebook_utils import ( + block_shape_to_group_size, +) +from torchao.quantization.quant_primitives import _DTYPE_TO_BIT_WIDTH +from torchao.utils import TorchAOBaseTensor + +# --- C++ Op Accessor Functions --- + + +def get_pack_op(weight_nbit: int): + """Gets the C++ packing function from the 'torchao' namespace.""" + op_name = f"_pack_groupwise_{weight_nbit}bit_weight_with_lut" + if not hasattr(torch.ops.torchao, op_name): + raise NotImplementedError(f"Packing op for {weight_nbit}-bit not found.") + return getattr(torch.ops.torchao, op_name) + + +def get_linear_op(weight_nbit: int): + """Gets the C++ fused linear function from the 'torchao' namespace.""" + op_name = f"_linear_groupwise_{weight_nbit}bit_weight_with_lut" + if not hasattr(torch.ops.torchao, op_name): + raise NotImplementedError(f"Linear op for {weight_nbit}-bit not found.") + return getattr(torch.ops.torchao, op_name) + + +aten = torch.ops.aten + + +class CodebookQuantizedPackedTensor(TorchAOBaseTensor): + tensor_data_names = [ + "packed_weight", + ] + tensor_attribute_names = [ + "bit_width", + "lut_block_size", + "scale_block_size", + "shape", + "dtype", + ] + + def __new__( + cls, packed_weight, bit_width, lut_block_size, scale_block_size, shape, dtype + ): + kwargs = { + "device": packed_weight.device, + "dtype": dtype, + "requires_grad": False, + } + return torch.Tensor._make_wrapper_subclass(cls, shape, **kwargs) + + def __init__( + self, + packed_weight: torch.Tensor, + bit_width: int, + lut_block_size: List[int], + scale_block_size: Optional[List[int]], + shape: torch.Size, + dtype: torch.dtype, + ): + self.packed_weight = packed_weight + self.bit_width = bit_width + self.lut_block_size = lut_block_size + self.scale_block_size = scale_block_size + + @classmethod + def from_unpacked( + cls, + int_data: torch.Tensor, + luts: torch.Tensor, + scales: Optional[torch.Tensor], + bit_width: int, + lut_block_size: List[int], + scale_block_size: Optional[List[int]], + original_shape: torch.Size, + bias: Optional[torch.Tensor] = None, + ): + lut_group_size = block_shape_to_group_size(lut_block_size, int_data.shape) + + if scale_block_size is not None and scales is not None: + # Scales are present, calculate group size + scale_group_size = block_shape_to_group_size( + scale_block_size, int_data.shape + ) + scales_arg = scales + else: + # Scales are not present, provide safe defaults + scale_group_size = -1 + scales_arg = torch.empty(0, dtype=luts.dtype, device=luts.device) + + pack_op = get_pack_op(bit_width) + packed_weight = pack_op( + int_data, luts, scale_group_size, lut_group_size, scales_arg, bias + ) + return cls( + packed_weight, + bit_width, + lut_block_size, + scale_block_size, + original_shape, + int_data.dtype, + ) + + @classmethod + def from_codebook_quantized_tensor( + cls, + tensor: CodebookQuantizedTensor, + *, + bias: Optional[torch.Tensor] = None, + ): + """ + Factory method to create a packed tensor from a CodebookQuantizedTensor. + + This method takes the general components of a codebook-quantized tensor + (codes, codebook, etc.) and uses a specialized 'pack_op' to fuse them + into a single, efficient tensor format suitable for high-performance + inference kernels. + """ + lut_block_size = tensor.block_size + lut_group_size = block_shape_to_group_size(lut_block_size, tensor.shape) + + # CoreML quantization scheme does not use scales, so they are disabled. + scale_group_size = -1 + scales = None + + bit_width = _DTYPE_TO_BIT_WIDTH[tensor.code_dtype] + # Retrieve the appropriate packing C++/CUDA kernel for the given bit width. + pack_op = get_pack_op(bit_width) + + # Ensure the codebook (Look-Up Table) is in float32, as this is the + # data type expected by the underlying packing kernel. + codebook = tensor.codebook.to(torch.float32) + + # --- Explanation for .squeeze() --- + # The input `tensor.codebook` is often stored in a 4D format, such as + # [1, num_groups, 256, 1], for compatibility with generic operators like + # the dequantize function. However, the specialized `pack_op` expects a + # more compact 2D LUT of shape [num_groups, 256]. + # The .squeeze() operation removes the unnecessary singleton (size 1) + # dimensions to achieve this required 2D format. + codebook = codebook.squeeze() + + # Call the packing operator to create the final fused tensor. + packed_weight = pack_op( + tensor.codes, codebook, scale_group_size, lut_group_size, scales, bias, None + ) + + # Return a new instance of this class containing the final packed weight + # and its associated quantization metadata. + return cls( + packed_weight, bit_width, lut_block_size, None, tensor.shape, tensor.dtype + ) + + +implements = CodebookQuantizedPackedTensor.implements +implements_torch_function = CodebookQuantizedPackedTensor.implements_torch_function + + +@implements_torch_function(F.linear) +def _(func, types, args, kwargs): + """ + Override for `torch.nn.functional.linear` specifically for the + GroupwiseLutQuantizedTensor. This calls the fused C++ kernel. + """ + input_tensor, weight_tensor, _ = ( + args[0], + args[1], + args[2] if len(args) > 2 else None, + ) + linear_op = get_linear_op(weight_tensor.bit_width) + lut_group_size = block_shape_to_group_size( + weight_tensor.lut_block_size, weight_tensor.shape + ) + original_shape = input_tensor.shape + k = weight_tensor.shape[1] + if input_tensor.dim() > 2: + input_tensor = input_tensor.reshape(-1, k) + + n = weight_tensor.shape[0] + output = linear_op( + input_tensor, weight_tensor.packed_weight, -1, lut_group_size, n, k + ) + + if len(original_shape) > 2: + output_shape = original_shape[:-1] + (n,) + return output.reshape(output_shape) + return output + + +@implements([aten.detach.default]) +def _(func, types, args, kwargs): + return return_and_correct_aliasing( + func, args, kwargs, args[0]._apply_fn_to_data(torch.detach) + ) + + +@implements(aten.clone.default) +def _(func, types, args, kwargs): + return return_and_correct_aliasing( + func, args, kwargs, args[0]._apply_fn_to_data(torch.clone) + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook_utils/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook_utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..509ae888397643b1416dd2488519afe81cda5d79 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook_utils/__init__.py @@ -0,0 +1,17 @@ +from .codebook_utils import ( + block_shape_to_group_size, + dequantize_dispatch, + group_size_to_block_shapes, + load_quantized_data, + quantize_dispatch, + save_quantized_data, +) + +__all__ = [ + "quantize_dispatch", + "dequantize_dispatch", + "save_quantized_data", + "load_quantized_data", + "block_shape_to_group_size", + "group_size_to_block_shapes", +] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook_utils/codebook_utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook_utils/codebook_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d80292f5c9bb79fc6080ac4947c52db5ba3a546c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/codebook_utils/codebook_utils.py @@ -0,0 +1,501 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. +# core ml support scale.. +import os +from typing import Any, Dict, List, Optional, Tuple + +import torch + +from torchao.prototype.quantization.codebook.codebook_ops import ( + choose_qparams_codebook, + dequantize_codebook, + quantize_codebook, +) +from torchao.prototype.quantization.codebook_coreml.codebook_ops import ( + choose_qparams_and_quantize_codebook_coreml, +) +from torchao.prototype.quantization.codebook_coreml.codebook_ops import ( + dequantize_codebook as dequantize_codebook_coreml, +) +from torchao.quantization.quant_primitives import _DTYPE_TO_BIT_WIDTH + + +def block_shape_to_group_size(block_shape, tensor_shape): + """Calculates the total number of elements in a group from a block_shape.""" + n_group, k_group = block_shape + n_dim, k_dim = tensor_shape + + if n_group == -1: + n_group = n_dim + if k_group == -1: + k_group = k_dim + + return n_group * k_group + + +def group_size_to_block_shapes( + lut_group_size: int, + tensor_shape: Tuple[int, int], +) -> Tuple[List[int], Optional[List[int]]]: + """ + Translates legacy integer-based group sizes into the new block_shape list format. + + This function encodes the implicit assumptions of the old system: + - LUTs were always grouped by rows. + - Scales were always grouped by columns. + + Args: + lut_group_size (int): The total number of elements that shared a single LUT. + tensor_shape (Tuple[int, int]): The shape of the weight tensor (N, K). + This is required to calculate the number of rows for the LUT group. + + Returns: + A tuple containing: + - lut_block_shape (List[int]): The new block shape for LUTs (e.g., [N, -1]). + - scale_block_shape (Optional[List[int]]): The new block shape for scales + (e.g., [-1, K]), or None. + """ + n_rows, k_cols = tensor_shape + + # --- 1. Translate LUT Group Size --- + if lut_group_size % k_cols != 0: + raise ValueError( + f"lut_group_size ({lut_group_size}) must be divisible by the number " + f"of columns ({k_cols}) for legacy row-grouping." + ) + rows_per_lut = lut_group_size // k_cols + lut_block_shape = [rows_per_lut, -1] + + return lut_block_shape + + +@torch.no_grad() +def _quantize_row_wise_group_with_scales( + input_tensor: torch.Tensor, + rows_per_group: int, + scale_block_shape: List[int], + code_dtype: torch.dtype, +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Quantizes a 2D tensor using row-wise grouping, with a unique LUT and + set of scales for each group. + + Returns a tuple of (codes, luts, scales) with structured shapes. + """ + assert input_tensor.ndim == 2, "This function expects a 2D tensor." + n_rows, k_cols = input_tensor.shape + assert n_rows % rows_per_group == 0, ( + f"Tensor rows ({n_rows}) must be divisible by rows_per_group ({rows_per_group})." + ) + + num_groups = n_rows // rows_per_group + list_of_luts, list_of_codes, list_of_scales = [], [], [] + + for i in range(num_groups): + start_row = i * rows_per_group + end_row = start_row + rows_per_group + tensor_slice = input_tensor[start_row:end_row, :] + + # This performs scalar quantization (block_size=(1, 1)) on the slice + codebook, scales = choose_qparams_codebook( + tensor_slice, + block_size=(1, 1), + scale_block_size=scale_block_shape[-1], + code_dtype=code_dtype, + ) + + codes = quantize_codebook( + tensor_slice, + codebook, + scales, + code_dtype=code_dtype, + ) + + # Append results without flattening + # Squeeze codebook from (codebook_size, 1, 1) to (codebook_size,) + list_of_luts.append(codebook.squeeze()) + list_of_scales.append(scales) + list_of_codes.append(codes) + + # Concatenate along the row dimension (dim=0) to preserve structure + final_codes = torch.cat(list_of_codes, dim=0) + final_scales = torch.cat(list_of_scales, dim=0) + + # Stack LUTs to create a (num_groups, codebook_size) tensor + final_luts = torch.stack(list_of_luts, dim=0) + final_scales = final_scales.flatten() + return final_codes, final_luts, final_scales + + +@torch.no_grad() +def _dequantize_row_wise_group_with_scales( + codes: torch.Tensor, + luts: torch.Tensor, + scales: torch.Tensor, + rows_per_group: int, + scale_group_size: int, + output_dtype: torch.dtype = torch.float32, +) -> torch.Tensor: + """ + Dequantizes a 2D tensor that was quantized with `quantize_per_row_group_with_scales`. + + Args: + codes (torch.Tensor): The quantized data codes. + Shape: (total_rows, total_cols) + luts (torch.Tensor): The lookup tables (codebooks) for each group. + Shape: (num_groups, codebook_size) + scales (torch.Tensor): The scale factors for each row. + Shape: (total_rows,) + rows_per_group (int): The number of rows in each quantization group. + output_dtype (torch.dtype): The desired data type for the output tensor. + + Returns: + torch.Tensor: The dequantized tensor. + Shape: (total_rows, total_cols) + """ + assert codes.ndim == 2, "This function expects a 2D codes tensor." + n_rows, k_cols = codes.shape + assert n_rows % rows_per_group == 0, ( + f"Tensor rows ({n_rows}) must be divisible by rows_per_group ({rows_per_group})." + ) + + # Calculate the number of row groups. + # e.g., if n_rows=128 and rows_per_group=4, num_groups=32 + num_groups = n_rows // rows_per_group + assert luts.shape[0] == num_groups, ( + "Mismatch between number of LUTs and row groups." + ) + + # calculate the number of scale blocks per row. + num_scale_blocks = k_cols // scale_group_size + # Reshape the flattened scales back to their original 3D structure. + # Shape: (n_rows, num_scale_blocks, 1) + reshaped_scales = scales.view(n_rows, num_scale_blocks, 1) + + # Pre-allocate the output tensor for efficiency to avoid creating new tensors in the loop. + # Shape: (total_rows, total_cols) + dequantized_tensor = torch.empty_like(codes, dtype=output_dtype) + + # Iterate over each group of rows to dequantize them chunk by chunk. + for i in range(num_groups): + # Calculate the start and end row indices for the current group slice. + start_row = i * rows_per_group + end_row = start_row + rows_per_group + + # Get the slice of codes for the current group. + # Shape: (rows_per_group, total_cols), e.g., (4, 64) + codes_slice = codes[start_row:end_row, :] + # Get the lookup table (codebook) for the current group. + # The LUT is 1D, shape: (codebook_size,), e.g., (2,) for 1-bit quantization. + # Reshape it to the (k, b1, b2) format required by dequantize_codebook. + # For scalar quantization, block sizes b1 and b2 are 1. + # Reshaped Shape: (codebook_size, 1, 1), e.g., (2, 1, 1) + current_lut = luts[i].view(-1, 1, 1) + + # Get the slice of scales corresponding to the rows in this group. + scales_slice = reshaped_scales[start_row:end_row, :, :] + + # Dequantize the slice using the dedicated function. + dequant_slice = dequantize_codebook( + codes=codes_slice, + codebook=current_lut, + scales=scales_slice, + output_dtype=output_dtype, + ) + # The returned `dequant_slice` has its original shape restored. + # Shape: (rows_per_group, total_cols), e.g., (4, 64) + + # Place the dequantized slice into the correct position in the final tensor. + dequantized_tensor[start_row:end_row, :] = dequant_slice + + return dequantized_tensor + + +@torch.no_grad +def quantize_flexible_grouping( + input_tensor: torch.Tensor, + lut_block_shape: List[int], + code_dtype: torch.dtype, +) -> Tuple[torch.Tensor, torch.Tensor, None]: + """ + Quantizes a tensor using either row-wise or column-wise grouping. + + Args: + input_tensor (torch.Tensor): The 2D tensor to be quantized. + Shape: (n_rows, k_cols) + lut_block_shape (List[int]): Defines the grouping strategy. + - To group by columns: `[-1, k_group]`. + - To group by rows: `[n_group, -1]`. + code_dtype (torch.dtype): The dtype for the codes (e.g., torch.uint4). + + Returns: + A tuple containing the quantized codes, the lookup tables, and None. + - final_codes (torch.Tensor): Quantized data of shape (n_rows, k_cols). + - final_luts (torch.Tensor): The codebook of lookup tables. + Shape: (num_groups, 2**nbits), where num_groups depends on the strategy. + - None: Placeholder for scales, which are not computed. + """ + assert input_tensor.ndim == 2, "This function expects a 2D tensor." + assert len(lut_block_shape) == 2, ( + "lut_block_shape must have two elements for a 2D tensor." + ) + n_rows, k_cols = input_tensor.shape + n_group, k_group = lut_block_shape + + # STRATEGY 1: Group by ROWS (e.g., block_size = [2, -1]) + if n_group != -1 and k_group == -1: + assert n_rows % n_group == 0, ( + f"Tensor rows ({n_rows}) must be divisible by row group size ({n_group})." + ) + list_of_luts, list_of_codes = [], [] + for i in range(0, n_rows, n_group): + tensor_slice = input_tensor[i : i + n_group, :] + lut, codes = choose_qparams_and_quantize_codebook_coreml( + input_tensor=tensor_slice, + code_dtype=code_dtype, + block_size=[-1, -1], + ) + list_of_luts.append(lut) + list_of_codes.append(codes) + + # Concatenate and remove singleton dimensions + final_luts = torch.cat(list_of_luts, dim=0).squeeze() + final_codes = torch.cat(list_of_codes, dim=0) + return final_codes, final_luts, None + + # STRATEGY 2: Group by COLUMNS (e.g., block_size = [-1, 64]) + elif n_group == -1: + if k_group != -1: + assert k_cols % k_group == 0, ( + f"Tensor cols ({k_cols}) must be divisible by col group size ({k_group})." + ) + luts, codes = choose_qparams_and_quantize_codebook_coreml( + input_tensor=input_tensor, + code_dtype=code_dtype, + block_size=lut_block_shape, + ) + # Remove singleton dimensions + final_luts = luts.squeeze() + final_codes = codes + return final_codes, final_luts, None + + # Unsupported strategy + else: + raise NotImplementedError( + f"lut_block_shape pattern '{lut_block_shape}' is not supported." + ) + + +@torch.no_grad +def dequantize_with_flexible_grouping( + codes: torch.Tensor, + luts: torch.Tensor, + lut_block_shape: List[int], + code_dtype: torch.dtype, + output_dtype: torch.dtype = torch.float32, +) -> torch.Tensor: + assert codes.ndim == 2, "This function expects a 2D codes tensor." + n_rows, k_cols = codes.shape + n_group, k_group = lut_block_shape + + # STRATEGY 1: Grouping was by COLUMNS (e.g., block_shape = [-1, 64]) + if n_group == -1: + return dequantize_codebook_coreml( + codes=codes, + codebook=luts, + code_dtype=code_dtype, + block_size=lut_block_shape, + output_dtype=output_dtype, + ) + + # STRATEGY 2: Grouping was by ROWS (e.g., block_shape = [2, -1]) + elif n_group != -1 and k_group == -1: + assert n_rows % n_group == 0, ( + f"Tensor rows ({n_rows}) must be divisible by row group size ({n_group})." + ) + num_groups = n_rows // n_group + dequantized_tensor = torch.empty_like(codes, dtype=output_dtype) + + for i in range(num_groups): + start_row, end_row = i * n_group, (i + 1) * n_group + + # Get the chunk of codes and the single LUT for that chunk + codes_slice = codes[start_row:end_row, :] + current_lut = luts[i] + + # To dequantize a chunk with a *single* LUT, we tell the primitive + # that the block_size should cover all columns (k_cols). + dequant_slice = dequantize_codebook_coreml( + codes=codes_slice, + # The primitive expects a 2D LUT of shape (num_luts, ...). + # Since we have one LUT, we must add a dimension. + codebook=current_lut.unsqueeze(0), + code_dtype=code_dtype, + block_size=[-1, k_cols], + output_dtype=output_dtype, + ) + dequantized_tensor[start_row:end_row, :] = dequant_slice + return dequantized_tensor + + else: + raise NotImplementedError( + f"lut_block_shape pattern '{lut_block_shape}' is not supported." + ) + + +def quantize_dispatch( + input_tensor: torch.Tensor, + lut_block_shape: List[int], + code_dtype: torch.dtype, + scale_block_shape: Optional[List[int]] = None, # Make this optional + backend: str = "auto", +) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]: + """ + Single entry point for quantization that dispatches to the correct backend. + + This function uses lut_block_shape to determine the quantization strategy, + allowing for flexible grouping by either rows or columns. + + Args: + input_tensor (torch.Tensor): The 2D tensor to be quantized (N, K). + lut_block_shape (List[int]): Defines the grouping for the look-up table. + - To group by N rows: use `[N, -1]`. + - To group by K columns: use `[-1, K]`. + code_dtype (torch.dtype): The target dtype for the codes (e.g., torch.uint4). + scale_block_shape (Optional[List[int]]): Defines grouping for scale factors, + used only by the 'scale' backend. E.g., `[-1, 64]`. If provided, + the 'scale' backend is used in "auto" mode. Defaults to None. + backend (str): The quantization backend to use. Can be "auto", "coreml", + or "scale". "auto" chooses based on whether `scale_block_shape` is provided. + + Returns: + Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]: A tuple + containing the (codes, luts, scales). Scales will be None for the + 'coreml' backend. + """ + # Determine which backend to use based on if scale_block_shape is provided. + if backend == "auto": + backend = "scale" if scale_block_shape is not None else "coreml" + + # Dispatch to the appropriate backend implementation + if backend == "scale": + if scale_block_shape is None: + raise ValueError( + "'scale' backend requires a `scale_block_shape` to be set." + ) + + # The 'scale' backend only supports row-grouping for the LUT. + # We derive the rows_per_group from the lut_block_shape parameter. + n_group, k_group = lut_block_shape + if n_group == -1 or k_group != -1: + raise ValueError( + "The 'scale' backend currently only supports row-grouping for LUTs. " + "Please use a `lut_block_shape` of `[N, -1]`." + ) + rows_per_lut_group = n_group + + codes, luts, scales = _quantize_row_wise_group_with_scales( + input_tensor, + rows_per_lut_group, + scale_block_shape, + code_dtype, + ) + + elif backend == "coreml": + codes, luts, scales = quantize_flexible_grouping( + input_tensor, lut_block_shape, code_dtype + ) + + else: + raise ValueError(f"Unknown backend: {backend}") + + luts = luts.to(torch.float32) + return codes, luts, scales + + +def dequantize_dispatch( + codes: torch.Tensor, + luts: torch.Tensor, + scales: Optional[torch.Tensor], + lut_block_shape: List[int], + scale_block_shape: Optional[List[int]] = None, + backend: str = "auto", + code_dtype: torch.dtype = torch.int4, + output_dtype: torch.dtype = torch.float32, +) -> torch.Tensor: + """ + Single entry point for dequantization that dispatches to the correct backend. + (Updated to use flexible block shapes). + """ + if backend == "auto": + # Use presence of scales to determine backend + backend = "scale" if scales is not None else "coreml" + + if backend == "scale": + # For backward compatibility, derive old integer args from new block shapes + if scale_block_shape is None: + raise ValueError("'scale' backend requires a `scale_block_shape`.") + + n_group, k_group = lut_block_shape + if k_group != -1: + raise ValueError( + "Scale dequant backend only supports row-grouped LUTs ([N, -1])." + ) + rows_per_lut_group = n_group + + scale_n_group, scale_k_group = scale_block_shape + if scale_n_group != 1: + raise ValueError( + "Scale dequant backend only supports col-grouped scales ([1, K])." + ) + scale_group_size = scale_k_group + + return _dequantize_row_wise_group_with_scales( + codes, + luts, + scales, + rows_per_lut_group, + scale_group_size, + output_dtype=output_dtype, + ) + + elif backend == "coreml": + # Perform grouping along rows, reshape the [Rows per group, 2**nbits] LUTs + # to [1, Rows per group, 2**nbits, 1] for the dequantize primitive. + num_luts = luts.shape[0] + lut_size = luts.shape[1] + luts_4d = luts.reshape(num_luts, 1, lut_size, 1) + return dequantize_codebook_coreml( + codes, + luts_4d, + _DTYPE_TO_BIT_WIDTH[code_dtype], + lut_block_shape, + output_dtype=output_dtype, + ) + + else: + raise ValueError(f"Unknown backend: {backend}") + + +def save_quantized_data(data: Dict[str, Any], filepath: str): + """ + Saves the dictionary of quantized tensors to a file. + """ + # Create the directory if it doesn't exist + os.makedirs(os.path.dirname(filepath), exist_ok=True) + torch.save(data, filepath) + print(f"Saved quantization results to '{filepath}'") + + +def load_quantized_data(filepath: str) -> Optional[Dict[str, Any]]: + """ + Loads the dictionary of quantized tensors from a file if it exists. + """ + if not os.path.exists(filepath): + return None + data = torch.load(filepath) + print(f"Loaded quantization results from cache: '{filepath}'") + return data diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/embedding/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/embedding/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/embedding/api.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/embedding/api.py new file mode 100644 index 0000000000000000000000000000000000000000..a5712782c21a9c4cc4bf00b124c5d62250e3a846 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/embedding/api.py @@ -0,0 +1,420 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import logging +import sys +from typing import Callable, List, Mapping, Optional, Tuple + +import torch +import torch.nn as nn + +from torchao.quantization.quantize_.workflows.intx.intx_opaque_tensor import ( + _is_kernel_library_loaded, +) + +logger = logging.getLogger(__name__) +logger.setLevel(logging.WARNING) + + +handler = logging.StreamHandler(sys.stdout) +formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") +handler.setFormatter(formatter) +logger.addHandler(handler) + + +from torchao.quantization.granularity import Granularity, PerAxis, PerGroup +from torchao.quantization.quant_api import ( + Int8DynamicActivationIntxWeightConfig, + IntxWeightOnlyConfig, + MappingType, + quantize_, +) +from torchao.quantization.quant_primitives import _DTYPE_TO_BIT_WIDTH + + +class QuantizedEmbedding(nn.Module): + def __init__( + self, + bit_width, + ): + super().__init__() + self.bit_width = bit_width + + def quantize_and_pack_weights(self, weights, group_size, mapping_type): + num_embeddings, embedding_dim = weights.shape + + embedding = torch.nn.Embedding(num_embeddings, embedding_dim) + embedding.weight = weights + quantize_( + embedding, + IntxWeightOnlyConfig( + weight_dtype=getattr(torch, f"int{self.bit_width}"), + granularity=PerGroup(group_size) if group_size > 0 else PerAxis(0), + mapping_type=mapping_type, + ), + lambda m, fqn: isinstance(m, torch.nn.Embedding), + ) + + weight_qvals = embedding.weight.qdata + weight_scales = embedding.weight.scale + weight_zeros = embedding.weight.zero_point + + assert weight_zeros is not None + weight_scales = weight_scales.reshape(num_embeddings, -1) + weight_zeros = weight_zeros.reshape(num_embeddings, -1).to(torch.int8) + self.register_buffer( + "packed_weight_qvals", + getattr(torch.ops.torchao, f"_pack_embedding_{self.bit_width}bit")( + weight_qvals.to(torch.int8) + ), + ) + self.num_embeddings = num_embeddings + self.embedding_dim = embedding_dim + self.register_buffer("weight_scales", weight_scales) + self.register_buffer("weight_zeros", weight_zeros) + + def forward(self, x): + shape = x.shape + return getattr(torch.ops.torchao, f"_embedding_{self.bit_width}bit")( + self.packed_weight_qvals, + self.num_embeddings, + self.embedding_dim, + self.weight_scales, + # embedding op requires weight_zeros be passed, even if they are all 0 + self.weight_zeros, + x.reshape(-1), + ).reshape(*shape, -1) + + +class QuantizedEmbeddingFallback(nn.Module): + def __init__( + self, + bit_width, + ): + super().__init__() + self.bit_width = bit_width + + def quantize_and_pack_weights(self, weights, group_size, mapping_type): + self.embedding = torch.nn.Embedding(*weights.shape) + self.embedding.weight = weights + quantize_( + self.embedding, + IntxWeightOnlyConfig( + weight_dtype=getattr(torch, f"int{self.bit_width}"), + granularity=PerGroup(group_size) if group_size > 0 else PerAxis(0), + mapping_type=mapping_type, + ), + lambda m, fqn: isinstance(m, torch.nn.Embedding), + ) + + def forward(self, x): + return self.embedding(x) + + +class QuantizedTiedEmbedding(nn.Module): + def __init__(self, bit_width, unembedding_packed_weights, group_size, n, k): + super().__init__() + self.bit_width = bit_width + self.register_buffer("unembedding_packed_weights", unembedding_packed_weights) + self.n = n + self.k = k + if group_size == -1: + self.group_size = k + else: + self.group_size = group_size + self.shared_embedding_op = getattr( + torch.ops.torchao, f"_shared_embedding_{bit_width}bit" + ) + + def forward(self, x): + shape = x.shape + return self.shared_embedding_op( + self.unembedding_packed_weights, + self.group_size, + self.n, + self.k, + x.reshape(-1), + ).reshape(*shape, -1) + + +def _replace_embedding_with_quantized_embedding( + module: nn.Module, + kwargs={}, + fqn: str = "", +): + group_size = kwargs.get("group_size", None) + bit_width = kwargs.get("bit_width", None) + use_fallback = kwargs.get("use_fallback", None) + mapping_type = kwargs.get("mapping_type", None) + + assert not isinstance(module, nn.Embedding) + for name, child in module.named_children(): + child_fqn = f"{fqn}.{name}" if fqn != "" else name + + if not isinstance(child, nn.Embedding): + _replace_embedding_with_quantized_embedding(child, kwargs, child_fqn) + else: + assert child.weight.device == torch.device("cpu"), "Only CPU is supported" + assert child.weight.dtype == torch.float32, "Only float32 is supported" + + if use_fallback: + qembedding = QuantizedEmbeddingFallback(bit_width) + setattr(module, name, qembedding) + getattr(module, name).quantize_and_pack_weights( + child.weight, + group_size, + mapping_type, + ) + else: + assert _is_kernel_library_loaded(), ( + "torchao kernel library is not loaded" + ) + qembedding = QuantizedEmbedding(bit_width) + setattr(module, name, qembedding) + getattr(module, name).quantize_and_pack_weights( + child.weight, + group_size, + mapping_type, + ) + + +class EmbeddingQuantizer: + def __init__( + self, + weight_dtype: torch.dtype = torch.int4, + granularity: Granularity = PerAxis(0), + mapping_type: MappingType = MappingType.ASYMMETRIC, + use_fallback: bool = False, + ): + assert weight_dtype in [getattr(torch, f"int{i}") for i in range(1, 9)] + bit_width = _DTYPE_TO_BIT_WIDTH[weight_dtype] + + if isinstance(granularity, PerGroup): + group_size = granularity.group_size + elif isinstance(granularity, PerAxis): + assert granularity.axis == 0 + group_size = -1 + else: + raise ValueError(f"Unsupported granularity: {granularity}") + + self.bit_width = bit_width + self.group_size = group_size + self.use_fallback = use_fallback + self.mapping_type = mapping_type + + def quantize(self, model: nn.Module) -> nn.Module: + _replace_embedding_with_quantized_embedding( + model, + kwargs={ + "group_size": self.group_size, + "bit_width": self.bit_width, + "use_fallback": self.use_fallback, + "mapping_type": self.mapping_type, + }, + ) + return model + + +def _get_fqns_with_filter( + module: nn.Module, + filter_fn: Callable[Tuple[str, nn.Module], bool], + fqn: str, + fqns: List[str], +): + for name, child in module.named_children(): + child_fqn = f"{fqn}.{name}" if fqn != "" else name + if filter_fn(child, child_fqn): + fqns.append(child_fqn) + else: + _get_fqns_with_filter(child, filter_fn, child_fqn, fqns) + + +def get_fqns_with_filter( + module: nn.Module, filter_fn: Callable[Tuple[str, nn.Module], bool] +) -> List[str]: + fqns = [] + _get_fqns_with_filter(module, filter_fn, "", fqns) + return fqns + + +class QuantizedLinear(nn.Module): + def __init__(self, packed_weight, n, k, group_size, bit_width, bias): + super().__init__() + self.register_buffer("packed_weight", packed_weight) + self.n = n + self.k = k + self.group_size = group_size + self.bit_width = bit_width + self.bias = bias + + def _forward_2d(self, x): + assert x.dim() == 2 + m, k = x.shape + assert k == self.k + return getattr( + torch.ops.torchao, f"_linear_8bit_act_{self.bit_width}bit_weight" + )(x, self.packed_weight, self.group_size, self.n, self.k) + + def forward(self, x): + if x.dim() == 2: + res = self._forward_2d(x) + else: + assert x.dim() >= 3 + lead_shape = x.shape[0:-2] + m, k = x.shape[-2], x.shape[-1] + assert k == self.k + res = self._forward_2d(x.reshape(-1, k)) + res = res.reshape(*lead_shape, m, self.n) + + if self.bias is not None: + res = res + self.bias + return res + + +def get_parent_by_fqn(root: nn.Module, fqn: str): + parts = fqn.split(".") + if len(parts) == 1: + # e.g. "fqn" → parent is root, child is "fqn" + return root, parts[0] + + parent_fqn = ".".join(parts[:-1]) + child_name = parts[-1] + parent = dict(root.named_modules()).get(parent_fqn, None) + if parent is None: + raise KeyError(f"Parent module {parent_fqn} not found in model") + return parent, child_name + + +class TiedEmbeddingQuantizer: + def __init__( + self, + weight_dtype: torch.dtype = torch.int4, + granularity: Granularity = PerAxis(0), + mapping_type: MappingType = MappingType.ASYMMETRIC, + ): + self.weight_dtype = weight_dtype + self.granularity = granularity + self.mapping_type = mapping_type + + def quantize( + self, + model: nn.Module, + embedding_to_unembedding: Optional[Mapping[str, str]] = None, + ): + embedding_fqns = get_fqns_with_filter( + model, lambda m, fqn: isinstance(m, nn.Embedding) + ) + linear_fqns = get_fqns_with_filter( + model, lambda m, fqn: isinstance(m, nn.Linear) + ) + state_dict = model.state_dict() + + # If embedding_to_unembedding is not provided, automatically detect shared embeddings and unembeddings + if embedding_to_unembedding is None: + embedding_to_unembedding = {} + for embedding_fqn in embedding_fqns: + embedding_w = state_dict[embedding_fqn + ".weight"] + for linear_fqn in linear_fqns: + linear_w = state_dict[linear_fqn + ".weight"] + if embedding_w.shape == linear_w.shape and torch.allclose( + embedding_w, linear_w + ): + print( + f"Found shared embedding {embedding_fqn} and unembedding {linear_fqn}" + ) + if embedding_fqn not in embedding_to_unembedding: + embedding_to_unembedding[embedding_fqn] = linear_fqn + else: + raise ValueError( + f"Found multiple candidate unembeddings ({embedding_to_unembedding[embedding_fqn]}, {linear_fqn}) for embedding {embedding_fqn}. This is not supported yet. Please explicitly define the input embedding_to_unembedding." + ) + + # Construct reverse mapping + unembedding_to_embedding = {} + for v, k in embedding_to_unembedding.items(): + if k not in unembedding_to_embedding: + unembedding_to_embedding[k] = v + else: + raise ValueError( + f"Found multiple candidate embeddings ({unembedding_to_embedding[k]}, {v}) for unembedding {k}. This is not supported yet." + ) + + # Check that embeddings are shared, embeddings are embeddings, and unembeddings are linear ops + for embedding_fqn, unembedding_fqn in embedding_to_unembedding.items(): + assert embedding_fqn in embedding_fqns, ( + f"Embedding {embedding_fqn} is not found in model" + ) + assert unembedding_fqn in linear_fqns, ( + f"Unembedding {unembedding_fqn} is not found in model" + ) + assert torch.allclose( + state_dict[embedding_fqn + ".weight"], + state_dict[unembedding_fqn + ".weight"], + ), ( + f"Embedding {embedding_fqn} does not share weights with unembedding {unembedding_fqn}" + ) + + # Quantize unembeddings + quantize_( + model, + Int8DynamicActivationIntxWeightConfig( + weight_dtype=self.weight_dtype, + weight_granularity=self.granularity, + weight_mapping_type=self.mapping_type, + # Only universal layout is supported for shared embedding + intx_packing_format="opaque_torchao_lowbit", + ), + filter_fn=lambda m, fqn: isinstance(m, nn.Linear) + and fqn in list(embedding_to_unembedding.values()), + ) + + embedding_fqn_to_quantized_unembedding = {} + for fqn, t in model.state_dict().items(): + if ( + fqn.endswith(".weight") + and fqn[: -len(".weight")] in unembedding_to_embedding + ): + embedding_fqn = unembedding_to_embedding[fqn[: -len(".weight")]] + embedding_fqn_to_quantized_unembedding[embedding_fqn] = t + + for embedding_fqn, unembedding_fqn in embedding_to_unembedding.items(): + weight = embedding_fqn_to_quantized_unembedding[embedding_fqn] + n, k = weight.shape + group_size = weight.block_size[1] + packed_weight = weight.packed_weights + bit_width = weight.bit_width + + # Set embedding + parent, child_name = get_parent_by_fqn(model, embedding_fqn) + child = getattr(parent, child_name) + assert n == child.num_embeddings, ( + "num_embeddings must match n in shared_unembedding" + ) + assert k == child.embedding_dim, ( + "embedding_dim must match k in shared_unembedding" + ) + setattr( + parent, + child_name, + QuantizedTiedEmbedding( + bit_width, + packed_weight, + group_size, + n, + k, + ), + ) + + # Set unembedding + parent, child_name = get_parent_by_fqn(model, unembedding_fqn) + child = getattr(parent, child_name) + if weight.packed_weights_has_bias: + assert child.bias is None + setattr( + parent, + child_name, + QuantizedLinear(packed_weight, n, k, group_size, bit_width, child.bias), + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/float8_static_quant/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/float8_static_quant/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9acecfd46d18a713338d8ea43f0ce31547ea2299 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/float8_static_quant/__init__.py @@ -0,0 +1,3 @@ +# (c) Meta Platforms, Inc. and affiliates. Confidential and proprietary. + +# pyre-strict diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/float8_static_quant/prototype_float8_tensor.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/float8_static_quant/prototype_float8_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..c0f3a5a959a13f124ffbe105d0d58e39629a1f01 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/float8_static_quant/prototype_float8_tensor.py @@ -0,0 +1,1153 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + + +from typing import List, Optional + +import torch +from torch.utils._python_dispatch import return_and_correct_aliasing + +from torchao.float8.inference import ( + Float8MMConfig, + FP8Granularity, + _is_1_128_scaled, + _is_128_128_scaled, + _is_rowwise_scaled, + _is_tensorwise_scaled, + _slice_scale_for_dimension, + addmm_float8_unwrapped_inference, + preprocess_data, + preprocess_scale, +) +from torchao.kernel.blockwise_quantization import ( + blockwise_fp8_gemm, +) +from torchao.quantization.granularity import PerRow, PerTensor +from torchao.quantization.quant_primitives import ( + _choose_scale_float8, + _dequantize_affine_float8, + _quantize_affine_float8, +) +from torchao.quantization.quantize_.common import ( + KernelPreference, + QuantizeTensorKwargs, +) +from torchao.quantization.quantize_.workflows import ( + QuantizeTensorToFloat8Kwargs, +) +from torchao.quantization.utils import get_block_size +from torchao.utils import ( + TorchAOBaseTensor, + _is_mslk_available, + fill_defaults, + is_sm_at_least_90, + is_sm_at_least_100, +) + +__all__ = [ + "PrototypeFloat8Tensor", + "_choose_quant_func_and_quantize_tensor", +] + +aten = torch.ops.aten + + +class PrototypeFloat8Tensor(TorchAOBaseTensor): + """ + Float8 Quantized (weight) Tensor, with float8 dynamic quantization for activation or bfloat16 activation. + + TODO: needs padding for cutlass kernels + + Tensor Attributes: + qdata: float8 raw data + scale: the scale for float8 Tensor + + Optional Tensor attributes: + act_quant_scale: the scale for activation, used for static quantization, used along with + act_quant_kwargs to quantize the activation statically + output_act_quant_scale: the scale for output activation, used when quantize_output=True + to quantize the output statically + + Non-Tensor Attributes: + block_size (List[int]): the block size for float8 quantization, meaning the shape of the elements + sharing the same set of quantization parameters (scale), have the same rank as qdata or + is an empty list (representing per tensor quantization) + mm_config (Float8MMConfig): Configuration for the matrix multiplication. Default uses fast accumulation. + act_quant_kwargs (QuantizeTensorToFloat8Kwargs): the kwargs for PrototypeFloat8Tensor.from_hp + kernel_preference (KernelPreference): the preference for quantize, mm etc. kernel to use, + by default, this will be chosen for user based on hardware, library availabilities etc. + dtype: Original Tensor dtype + output_act_quant_kwargs (QuantizeTensorToFloat8Kwargs): the kwargs for output quantization + """ + + tensor_data_names = ["qdata", "scale"] + optional_tensor_data_names = ["act_quant_scale", "output_act_quant_scale"] + tensor_attribute_names = [] + optional_tensor_attribute_names = [ + "block_size", + "mm_config", + "act_quant_kwargs", + "kernel_preference", + "dtype", + "output_act_quant_kwargs", + ] + + def __new__( + cls, + qdata: torch.Tensor, + scale: torch.Tensor, + act_quant_scale: Optional[torch.Tensor] = None, + output_act_quant_scale: Optional[torch.Tensor] = None, + block_size: Optional[List[int]] = None, + mm_config: Optional[Float8MMConfig] = None, + act_quant_kwargs: Optional[QuantizeTensorToFloat8Kwargs] = None, + kernel_preference: KernelPreference = KernelPreference.AUTO, + dtype: Optional[torch.dtype] = None, + output_act_quant_kwargs: Optional[QuantizeTensorToFloat8Kwargs] = None, + ): + shape = qdata.shape + kwargs = {} + kwargs["device"] = qdata.device + kwargs["dtype"] = dtype + kwargs["requires_grad"] = False + return torch.Tensor._make_wrapper_subclass(cls, shape, **kwargs) # type: ignore[attr-defined] + + def __init__( + self, + qdata: torch.Tensor, + scale: torch.Tensor, + act_quant_scale: Optional[torch.Tensor] = None, + output_act_quant_scale: Optional[torch.Tensor] = None, + block_size: Optional[List[int]] = None, + mm_config: Optional[Float8MMConfig] = None, + act_quant_kwargs: Optional[QuantizeTensorToFloat8Kwargs] = None, + kernel_preference: KernelPreference = KernelPreference.AUTO, + dtype: Optional[torch.dtype] = None, + output_act_quant_kwargs: Optional[QuantizeTensorToFloat8Kwargs] = None, + ): + super().__init__() + self.qdata = qdata + self.scale = scale + # we need a separate `act_quant_scale` instead of merging this into `act_quant_kwargs` + # because inductor does not fakify tensors attached to `act_quant_kwargs` properly + # currently + self.act_quant_scale = act_quant_scale + self.block_size = block_size + self.mm_config = mm_config + self.act_quant_kwargs = act_quant_kwargs + self.kernel_preference = kernel_preference + # output quantization attributes + self.output_act_quant_scale = output_act_quant_scale + self.output_act_quant_kwargs = output_act_quant_kwargs + + def __repr__(self): + return ( + f"{self.__class__.__name__}({self.act_quant_kwargs=}, {self.qdata=}, {self.scale=}, " + f"{self.act_quant_scale=}, {self.output_act_quant_scale=}, {self.block_size=}, {self.mm_config=}, {self.kernel_preference=} " + f"{self.shape=}, {self.device=}, {self.dtype=})" + ) + + def _quantization_type(self): + return f"{self.act_quant_kwargs=}, {self.block_size=}, {self.mm_config=}, {self.scale.shape=}, {self.kernel_preference=}" + + def dequantize(self, output_dtype: Optional[torch.dtype] = None) -> torch.Tensor: + if output_dtype is None: + output_dtype = self.dtype + + qdata, scale = self.qdata, self.scale + return _dequantize_affine_float8(qdata, scale, output_dtype) + + @classmethod + def from_hp( + cls, + hp_tensor: torch.Tensor, + float8_dtype: torch.dtype = torch.float8_e4m3fn, + granularity: FP8Granularity = PerRow(), + mm_config: Optional[Float8MMConfig] = None, + hp_value_lb: Optional[float] = None, + hp_value_ub: Optional[float] = None, + kernel_preference: KernelPreference = KernelPreference.AUTO, + act_quant_kwargs: Optional[QuantizeTensorToFloat8Kwargs] = None, + scale: Optional[torch.Tensor] = None, + act_quant_scale: Optional[torch.Tensor] = None, + output_act_quant_scale: Optional[torch.Tensor] = None, + output_act_quant_kwargs: Optional[QuantizeTensorToFloat8Kwargs] = None, + ): + block_size = get_block_size(hp_tensor.shape, granularity) + block_size = list(block_size) + + # If scale is provided (for static quantization), use it directly + if scale is not None: + # Verify scale dimensions match expected block structure + assert scale.ndim == hp_tensor.ndim + assert all( + (hp_tensor.shape[i] // block_size[i]) == scale.shape[i] + for i in range(hp_tensor.ndim) + ) + data = _quantize_affine_float8(hp_tensor, scale, float8_dtype) + hp_dtype = hp_tensor.dtype + return PrototypeFloat8Tensor( + data, + scale, + block_size=block_size, + mm_config=mm_config, + act_quant_kwargs=act_quant_kwargs, + kernel_preference=kernel_preference, + dtype=hp_dtype, + act_quant_scale=act_quant_scale, + output_act_quant_scale=output_act_quant_scale, + output_act_quant_kwargs=output_act_quant_kwargs, + ) + + kernel_choice = None + if ( + kernel_preference == KernelPreference.AUTO + and _is_mslk_available() + and is_sm_at_least_90() + and isinstance(granularity, PerRow) + # mslk path only supports quantizing along the last dim + and granularity.dim in (-1, len(hp_tensor.shape) - 1) + and float8_dtype == torch.float8_e4m3fn + and hp_value_lb is None + ): + # if kernel_preference is AUTO and per row quantization + # we'll use mslk quantize kernel for best performance + kernel_choice = "mslk" + elif kernel_preference == KernelPreference.MSLK: + # if user explicitly chose MSLK kernel preference, we'll also use mslk kernel + assert _is_mslk_available() and is_sm_at_least_90(), ( + "Specified mslk but mslk is not installed or hardware is not >= SM 9.0 (>= H100)" + ) + assert hp_value_lb is None, ( + "hp_value_lb should not be specified if with KernelPreference.MSLK" + ) + kernel_choice = "mslk" + else: + # fallback quantize kernel for everything else will be torch + kernel_choice = "torch" + + if kernel_choice == "mslk": + assert hp_value_lb is None, f"{hp_value_lb=} is not supported" + if hp_value_ub is not None: + maybe_hp_value_ub_tensor = torch.tensor( + hp_value_ub, dtype=torch.float, device=hp_tensor.device + ) + else: + maybe_hp_value_ub_tensor = None + if isinstance(granularity, PerRow): + data, scale = torch.ops.triton.quantize_fp8_row( + hp_tensor, scale_ub=maybe_hp_value_ub_tensor + ) + scale_shape = [] + for i in range(hp_tensor.ndim): + scale_shape.append(hp_tensor.shape[i] // block_size[i]) + scale = scale.reshape(*scale_shape) + else: + assert isinstance(granularity, PerTensor), ( + f"Expected per tensor, got {granularity}" + ) + # current error: torch.AcceleratorError: CUDA error: an illegal memory access was encountered + # TODO: enable after this is working + # data, scale = torch.ops.mslk.quantize_fp8_per_tensor( + # hp_tensor, num_tokens, scale_ub=maybe_hp_value_ub_tensor + # ) + raise NotImplementedError( + "Currently KernelPreference.MSLK does not work for per tensor float8 quant" + ) + else: + assert kernel_choice == "torch", f"Expected torch, got {kernel_choice}" + scale = _choose_scale_float8( + hp_tensor, + float8_dtype=float8_dtype, + block_size=block_size, + hp_value_lb=hp_value_lb, + hp_value_ub=hp_value_ub, + ) + data = _quantize_affine_float8(hp_tensor, scale, float8_dtype) + + hp_dtype = hp_tensor.dtype + return PrototypeFloat8Tensor( + data, + scale, + block_size=block_size, + mm_config=mm_config, + act_quant_kwargs=act_quant_kwargs, + kernel_preference=kernel_preference, + dtype=hp_dtype, + act_quant_scale=act_quant_scale, + output_act_quant_scale=output_act_quant_scale, + output_act_quant_kwargs=output_act_quant_kwargs, + ) + + +implements = PrototypeFloat8Tensor.implements +implements_torch_function = PrototypeFloat8Tensor.implements_torch_function + + +@implements(aten.linear.default) +@implements_torch_function(torch.nn.functional.linear) +def _(func, types, args, kwargs): + input_tensor, weight_tensor, bias = ( + args[0], + args[1], + args[2] if len(args) > 2 else None, + ) + result = _float8_addmm_impl(input_tensor, weight_tensor.t(), bias) + return result + + +@implements(aten.matmul.default) +@implements_torch_function(torch.matmul) +def _(func, types, args, kwargs): + input_tensor, weight_tensor = args[0], args[1] + return _float8_addmm_impl(input_tensor, weight_tensor) + + +@implements(aten.mm.default) +@implements_torch_function(torch.mm) +def _(func, types, args, kwargs): + input_tensor, weight_tensor = args[0], args[1] + return _float8_addmm_impl(input_tensor, weight_tensor) + + +@implements(aten.addmm_.default) +def _(func, types, args, kwargs): + bias_tensor, input_tensor, weight_tensor = ( + args[0], + args[1], + args[2], + ) + assert kwargs.get("alpha", 1) == 1, "only alpha=1 is supported" + assert kwargs.get("beta", 1) == 1, "only beta=1 is supported" + out = _float8_addmm_impl(input_tensor, weight_tensor) + return bias_tensor.add_(out) + + +def _float8_addmm_impl( + input_tensor: PrototypeFloat8Tensor, + weight_tensor: PrototypeFloat8Tensor, + bias: Optional[torch.Tensor] = None, +) -> torch.Tensor: + assert isinstance(weight_tensor, PrototypeFloat8Tensor), ( + f"Don't expect to reach here with an override other than weight currently, {type(input_tensor)} {type(weight_tensor)}" + ) + + act_quant_kwargs = weight_tensor.act_quant_kwargs + # quantize activation, if `act_quant_kwargs` is specified + if act_quant_kwargs is not None: + assert not isinstance(input_tensor, TorchAOBaseTensor), ( + "input tensor was already quantized" + ) + input_tensor = _choose_quant_func_and_quantize_tensor( + input_tensor, + act_quant_kwargs, + act_quant_scale=weight_tensor.act_quant_scale, + ) + + # TODO: technically addmm and mm don't support broadcasting, + # would be more correct to enforce x and w to be 2d here and + # move 3d support to matmul and linear + out_shape = (*input_tensor.shape[:-1], weight_tensor.shape[1]) + + if isinstance(input_tensor, PrototypeFloat8Tensor): + kernel_choice = None + + if weight_tensor.kernel_preference == KernelPreference.AUTO: + kernel_choice = "torch" + if ( + _is_mslk_available() + and is_sm_at_least_90() + and (not _is_128_128_scaled(weight_tensor)) + ): + kernel_choice = "mslk" + elif weight_tensor.kernel_preference == KernelPreference.MSLK: + kernel_choice = "mslk" + else: + assert weight_tensor.kernel_preference == KernelPreference.TORCH, ( + f"{weight_tensor.kernel_preference=} not handled" + ) + kernel_choice = "torch" + + if kernel_choice == "mslk": + assert _is_mslk_available(), "Expected mslk package to be installed" + assert is_sm_at_least_90(), "Expected SM90+ for mslk" + mm_config = weight_tensor.mm_config + assert mm_config is not None + assert not _is_128_128_scaled(weight_tensor), "unimplemented" + + xq = input_tensor.qdata.reshape(-1, input_tensor.qdata.shape[-1]) + x_scale = input_tensor.scale + if _is_rowwise_scaled(weight_tensor.t()): + assert _is_rowwise_scaled(input_tensor), ( + "Input tensor must be rowwise block size" + ) + res = torch.ops.mslk.f8f8bf16_rowwise( + xq, + weight_tensor.qdata.t(), + input_tensor.scale, + weight_tensor.scale.t(), + bias=bias, + use_fast_accum=mm_config.use_fast_accum, + ).reshape(out_shape) + else: + assert _is_tensorwise_scaled(weight_tensor) + assert _is_tensorwise_scaled(input_tensor) + res = torch.ops.mslk.f8f8bf16( + xq, + weight_tensor.qdata.t(), + x_scale * weight_tensor.scale.t(), + use_fast_accum=mm_config.use_fast_accum, + ).reshape(out_shape) + if bias is not None: + res = res + bias + else: + assert kernel_choice == "torch" + scaled_mm_config = weight_tensor.mm_config + assert scaled_mm_config is not None + + # Extract tensor data and scales + inpt_data = input_tensor.qdata.reshape(-1, input_tensor.qdata.shape[-1]) + w_data = weight_tensor.qdata + input_scale = input_tensor.scale + w_scale = weight_tensor.scale + + if _is_rowwise_scaled(weight_tensor): + assert _is_rowwise_scaled(input_tensor), ( + "Input tensor must be rowwise block size" + ) + elif _is_128_128_scaled(weight_tensor): + assert _is_1_128_scaled(input_tensor), ( + "input_tensor must be 1x128 scaled" + ) + + input_scale = preprocess_scale(input_scale, input_tensor.shape) + inpt_data, w_data = preprocess_data(inpt_data, w_data, scaled_mm_config) + + if _is_128_128_scaled(weight_tensor): + # TODO(future PR): add testing for torch._scaled_mm with + # blockwise scaling on CUDA 12.9 + # TODO(future PR): add mslk path if available + # TODO(future PR): proper out_dtype handling + assert _is_1_128_scaled(input_tensor), "unsupported" + res = blockwise_fp8_gemm( + inpt_data, + input_scale, + w_data.t(), + w_scale.t(), + block_size=128, + ) + if bias is not None: + res = res + bias + else: + res = addmm_float8_unwrapped_inference( + inpt_data, + input_scale, + w_data, + w_scale, + output_dtype=input_tensor.dtype, + bias=bias, + use_fast_accum=scaled_mm_config.use_fast_accum, + ) + res = res.reshape(out_shape) + else: + assert not isinstance(input_tensor, TorchAOBaseTensor), ( + "Expecting input_tensor to be unquantized" + ) + # when input is not `PrototypeFloat8Tensor`, we expect that it is not quantized + # so this is float8 weight only quantization + res = torch.matmul(input_tensor, weight_tensor.dequantize()) + if bias is not None: + res = res + bias + + # Handle output quantization if output_act_quant_kwargs is set + output_act_quant_kwargs = weight_tensor.output_act_quant_kwargs + if output_act_quant_kwargs is not None: + res = _choose_quant_func_and_quantize_tensor( + res, + output_act_quant_kwargs, + act_quant_scale=weight_tensor.output_act_quant_scale, + ) + # Dequantize the output to return a regular tensor + # This simulates the quantization error while keeping the output + # in a format that downstream ops can easily consume + res = res.dequantize() + + return res + + +@implements_torch_function(torch.bmm) +def _(func, types, args, kwargs): + input_tensor, weight_tensor = ( + args[0], + args[1], + ) + assert isinstance(weight_tensor, PrototypeFloat8Tensor), ( + f"Don't expect to reach here with an override other than weight currently, {type(input_tensor)} {type(weight_tensor)}" + ) + + kernel_preference = weight_tensor.kernel_preference + assert kernel_preference != KernelPreference.TORCH, "bmm is not supported for TORCH" + assert _is_mslk_available(), "bmm is not supported when mslk is not installed" + + orig_act_size = input_tensor.size() + act_quant_kwargs = weight_tensor.act_quant_kwargs + if act_quant_kwargs is not None: + input_tensor = _choose_quant_func_and_quantize_tensor( + input_tensor, + act_quant_kwargs, + act_quant_scale=weight_tensor.act_quant_scale, + ) + + if isinstance(input_tensor, PrototypeFloat8Tensor): + a_data = input_tensor.qdata + a_scale = input_tensor.scale + + b_data = weight_tensor.qdata + b_scale = weight_tensor.scale + + assert ( + weight_tensor.block_size[0] == 1 + and weight_tensor.block_size[1] == weight_tensor.shape[1] + and weight_tensor.block_size[2] == 1 + ), "bmm only works for per row weight quantization" + assert ( + all(x == 1 for x in input_tensor.block_size[:-1]) + and input_tensor.block_size[-1] == input_tensor.shape[-1] + ), "bmm only works for per row activation quantization" + + orig_out_features = b_data.shape[-1] + + res = torch.ops.mslk.f8f8bf16_rowwise_batched( + a_data, + b_data.transpose(-2, -1).contiguous(), + a_scale, + b_scale.transpose(-2, -1), + b_scale, + ) + res = res.reshape(*orig_act_size[:-1], orig_out_features) + else: + raise NotImplementedError( + "bmm only support float8 dynamic activation + float8 weight" + ) + + return res + + +def _quantize_and_scaled_conv3d( + input_tensor, + weight_tensor, + bias, + stride, + padding, + dilation, +): + assert isinstance(weight_tensor, PrototypeFloat8Tensor), ( + f"Don't expect to reach here with an override other than weight currently, {type(input_tensor)} {type(weight_tensor)}" + ) + + assert input_tensor.dim() == 5 and weight_tensor.dim() == 5, ( + "Only support 3D conv currently" + ) + assert _is_mslk_available(), "quantized fp8 conv3d requires mslk to be available" + act_quant_kwargs = weight_tensor.act_quant_kwargs + # quantize activation, if `act_quant_kwargs` is specified + if act_quant_kwargs is not None: + input_tensor = _choose_quant_func_and_quantize_tensor( + input_tensor, + act_quant_kwargs, + act_quant_scale=weight_tensor.act_quant_scale, + ) + + if isinstance(input_tensor, PrototypeFloat8Tensor): + kernel_choice = None + if weight_tensor.kernel_preference == KernelPreference.AUTO: + if _is_mslk_available() and is_sm_at_least_100(): + kernel_choice = "mslk" + else: + raise NotImplementedError( + f"No available kernel choice for {weight_tensor.kernel_preference}" + ) + elif weight_tensor.kernel_preference == KernelPreference.MSLK: + kernel_choice = "mslk" + else: + raise NotImplementedError( + f"No available kernel choice for {weight_tensor.kernel_preference}" + ) + + assert kernel_choice == "mslk", "Only mslk kernel choice is supported currently" + input_qdata = input_tensor.qdata + weight_qdata = weight_tensor.qdata + + is_input_channels_last = input_qdata.is_contiguous( + memory_format=torch.channels_last_3d + ) + is_weight_channels_last = weight_qdata.is_contiguous( + memory_format=torch.channels_last_3d + ) + + # convert the input/weight to channels_last_3d memory_format here + # to make sure we can call the mslk conv + # kernel, it should be a no-op if both activation and weight are in + # channels_last_3d memory_format + input_qdata = input_qdata.contiguous(memory_format=torch.channels_last_3d) + weight_qdata = weight_qdata.contiguous(memory_format=torch.channels_last_3d) + + # move C_in to last dim + # after permute: (N, D, H, W, C_in) + input_qdata = input_qdata.permute([0, 2, 3, 4, 1]) + + # move C_in to last dim + # after permute: (C_out, K1, K2, K3, C_in) + weight_qdata = weight_qdata.permute([0, 2, 3, 4, 1]) + + input_scale = input_tensor.scale + weight_scale = weight_tensor.scale + output = torch.ops.mslk.f8f8bf16_conv( + input_qdata, + weight_qdata, + input_scale * weight_scale, + padding, + stride, + dilation, + ) + # output shape after permute: N, C_out, D_out, H_out, W_out + output = output.permute([0, 4, 1, 2, 3]) + + # aligning the semantics with bfloat16 conv ops, the + # output should use contiguous_format if none of the input/weight + # are in channels_last format, otherwise, the output is already + # in channels_last format (from mslk kernel) + if not (is_input_channels_last or is_weight_channels_last): + output = output.contiguous() + return output + + +@implements(aten.convolution.default) +def _(func, types, args, kwargs): + """The semantics of memory_format will match high precision counterparts + i.e. if any of input or weight are in channels_last_3d format + the output will be in channels_last_3d format, otherwise the output + will be contiguous + """ + ( + input_tensor, + weight_tensor, + bias, + stride, + padding, + dilation, + transposed, + output_padding, + groups, + ) = args + assert not transposed, "transposed conv is not supported currently" + dim = len(output_padding) + assert dim in [2, 3], "Only 2d or 3d convs are supported" + assert groups == 1, f"Only 1 is supported for `groups`, got: {groups}" + + if dim == 2: + # (N, C, H, W) --> (N, C, 1, H, W) + input_tensor = input_tensor.unsqueeze(2) + weight_tensor = weight_tensor.unsqueeze(2) + if weight_tensor.act_quant_scale is not None: + weight_tensor.act_quant_scale = weight_tensor.act_quant_scale.unsqueeze(2) + + assert tuple(output_padding) == (0, 0), ( + f"Only (0, 0) is supported for `output_padding`, got: f{output_padding}" + ) + padding = [0, *padding] + stride = [1, *stride] + dilation = [1, *dilation] + res = _quantize_and_scaled_conv3d( + input_tensor, + weight_tensor, + bias, + stride, + padding, + dilation, + ) + assert res.shape[2] == 1 + res = res.squeeze(2) + return res + else: + assert tuple(output_padding) == (0, 0, 0), ( + f"Only (0, 0, 0) is supported for `output_padding`, got: f{output_padding}" + ) + return _quantize_and_scaled_conv3d( + input_tensor, + weight_tensor, + bias, + stride, + padding, + dilation, + ) + + +@implements(aten.conv3d.default) +def _(func, types, args, kwargs): + """The semantics of memory_format will match high precision counterparts + i.e. if any of input or weight are in channels_last_3d format + the output will be in channels_last_3d format, otherwise the output + will be contiguous + """ + ( + input_tensor, + weight_tensor, + bias, + stride, + padding, + dilation, + groups, + ) = fill_defaults(args, 7, [None, [1, 1, 1], [0, 0, 0], [1, 1, 1], 1]) + conv3d_output = _quantize_and_scaled_conv3d( + input_tensor, + weight_tensor, + bias, + stride, + padding, + dilation, + ) + return conv3d_output + + +@implements(aten.conv2d.default) +def _(func, types, args, kwargs): + """The semantics of memory_format will match high precision counterparts + i.e. if any of input or weight are in channels_last_3d format + the output will be in channels_last_3d format, otherwise the output + will be contiguous + """ + ( + input_tensor, + weight_tensor, + bias, + stride, + padding, + dilation, + groups, + ) = fill_defaults(args, 7, [None, [1, 1], [0, 0], [1, 1], 1]) + # (N, C, H, W) --> (N, C, 1, H, W) + input_tensor = input_tensor.unsqueeze(2) + weight_tensor = weight_tensor.unsqueeze(2) + if weight_tensor.act_quant_scale is not None: + weight_tensor.act_quant_scale = weight_tensor.act_quant_scale.unsqueeze(2) + + padding = [0, *padding] + stride = [1, *stride] + dilation = [1, *dilation] + res = _quantize_and_scaled_conv3d( + input_tensor, + weight_tensor, + bias, + stride, + padding, + dilation, + ) + assert res.shape[2] == 1 + res = res.squeeze(2) + return res + + +@implements(aten.slice.Tensor) +def _(func, types, args, kwargs): + """Supports slicing for 1d, 2d, and 3d tensors + original tensor shape has dimension (N, K), or (E, N, K) + qdata has dimension (N, K) or (E, N, K) + scale (per row quantization) has dimension: (N,) or (E, N) + + since qdata has the same dimension as original tensor, we can directly slice that + for scale, we'll do a slice when dim is 0, and don't need to do anything for dim 1 + + Note that we need to call slice on the qdata and scale directly because slice + is an operation that need to preserve aliasing + """ + self, dim, start, end, step = fill_defaults(args, 5, [0, None, None, 1]) + assert step == 1 + assert dim == 0 or dim == 1 or dim == 2, ( + f"Only dim==0,1,2 are supported, got: dim={dim}" + ) + if end >= self.shape[dim]: + end = self.shape[dim] + + assert self.qdata.ndim == 2 or self.qdata.ndim == 3, ( + f"Expected packed weight to have dim==2,3 got: dim={self.qdata.ndim}" + ) + + # Always slice the qdata + sliced_data = aten.slice.Tensor(self.qdata, dim, start, end, step) + + if self.scale.numel() == 1: + # Per-tensor quantization - scale doesn't change + sliced_scale = self.scale + else: + # Block-wise quantization - need to slice the scale appropriately + sliced_scale = _slice_scale_for_dimension( + self.scale, self.qdata.shape, dim, start, end, step + ) + + # adjust block_size since the shape has changed, block_size[i] should not be greater than shape[i] + block_size = self.block_size.copy() + for i in range(len(self.block_size)): + block_size[i] = min(block_size[i], sliced_data.shape[i]) + + return return_and_correct_aliasing( + func, + args, + kwargs, + PrototypeFloat8Tensor( + sliced_data, + sliced_scale, + act_quant_scale=self.act_quant_scale, + output_act_quant_scale=self.output_act_quant_scale, + block_size=block_size, + mm_config=self.mm_config, + act_quant_kwargs=self.act_quant_kwargs, + kernel_preference=self.kernel_preference, + dtype=self.dtype, + output_act_quant_kwargs=self.output_act_quant_kwargs, + ), + ) + + +@implements(aten.cat.default) +def _(func, types, args, kwargs): + """Concatenate multiple float8 quantized tensors + (scale and qdata has the same rank) + If the concatenation dimension is not the same as block_size, then we can just concatenate the + qdata and scale directly + If the concatention dimension is the same as block_size, theoretically we should either + (1) check that scales from all tensors are equal and use the first scale + (2) dequantize and requantize + but for now we just use the first scale directly, which might have slight implication on accuaracy + we can improve upon this a bit later + """ + + tensors, dim = fill_defaults(args, 2, [[], 0]) + tensor_0 = tensors[0] + dim = dim % tensor_0.ndim + + for i in range(1, len(tensors)): + assert tensor_0.qdata.ndim == tensors[i].qdata.ndim + assert tensor_0.scale.ndim == tensors[i].scale.ndim + assert tensor_0.block_size == tensors[i].block_size + assert tensor_0.mm_config == tensors[i].mm_config + assert tensor_0.act_quant_kwargs == tensors[i].act_quant_kwargs + assert tensor_0.kernel_preference == tensors[i].kernel_preference + + qdatas = [t.qdata for t in tensors] + scales = [t.scale for t in tensors] + + cat_qdata = aten.cat.default(qdatas, dim=dim) + if tensor_0.block_size[dim] == 1: + cat_scale = aten.cat.default(scales, dim=dim) + else: + for i in range(1, len(tensors)): + assert torch.equal(tensor_0.scale, tensors[i].scale) + cat_scale = scales[0] + + block_size = [] + for i in range(cat_qdata.ndim): + block_size.append(cat_qdata.shape[i] // cat_scale.shape[i]) + + new = tensor_0.__class__( + cat_qdata, + cat_scale, + act_quant_scale=tensor_0.act_quant_scale, + output_act_quant_scale=tensor_0.output_act_quant_scale, + block_size=block_size, + mm_config=tensor_0.mm_config, + act_quant_kwargs=tensor_0.act_quant_kwargs, + kernel_preference=tensor_0.kernel_preference, + dtype=tensor_0.dtype, + output_act_quant_kwargs=tensor_0.output_act_quant_kwargs, + ) + return return_and_correct_aliasing(func, args, kwargs, new) + + +@implements(aten.transpose.int) +def _(func, types, args, kwargs): + self, dim0, dim1 = args + qdata = self.qdata.transpose(dim0, dim1) + scale = self.scale.transpose(dim0, dim1) + block_size = self.block_size.copy() + + block_size[dim0], block_size[dim1] = block_size[dim1], block_size[dim0] + + new = self.__class__( + qdata, + scale, + act_quant_scale=self.act_quant_scale, + output_act_quant_scale=self.output_act_quant_scale, + block_size=block_size, + mm_config=self.mm_config, + act_quant_kwargs=self.act_quant_kwargs, + kernel_preference=self.kernel_preference, + dtype=self.dtype, + output_act_quant_kwargs=self.output_act_quant_kwargs, + ) + return return_and_correct_aliasing(func, args, kwargs, new) + + +@implements(aten.view.default) +def _(func, types, args, kwargs): + self, size = args + original_shape = self.shape + if len(original_shape) == 3 and len(size) == 2: + assert original_shape[-1] == size[-1], ( + f"Only support reshaping when last dimension matches, requested: reshaping from {original_shape} to {size}" + ) + # TODO: this seems wrong, we should merge the first two dimensions instead + qdata = self.qdata.reshape(*size) + scale = self.scale.reshape(*size) + block_size = self.block_size.copy() + block_size = [block_size[0] * block_size[1], block_size[2]] + elif len(original_shape) == 2 and len(size) == 3: + assert original_shape[-1] == size[-1], ( + f"Only support reshaping when last dimension matches, requested: reshaping from {original_shape} to {size}" + ) + qdata = self.qdata.reshape(*size) + block_size = self.block_size.copy() + block_size = [1, block_size[0], block_size[1]] + scale_shape = [] + for i in range(3): + scale_shape.append(qdata.shape[i] // block_size[i]) + scale = self.scale.reshape(*scale_shape) + elif len(original_shape) == len(size): + assert all(x == y or y == -1 for x, y in zip(original_shape, size)), ( + f"Only support viewing with match dimensions or -1, got: {original_shape}, {size}" + ) + qdata = self.qdata.reshape(*size) + scale_shape = [] + for i in range(3): + scale_shape.append(qdata.shape[i] // self.block_size[i]) + scale = self.scale.reshape(*scale_shape) + block_size = self.block_size + else: + assert len(original_shape) == 2 and len(size) == 3, ( + f"Only support reshaping from 2D to 3D or from 3D to 2D, requested: reshaping from {original_shape} to {size}" + ) + + new = self.__class__( + qdata, + scale, + act_quant_scale=self.act_quant_scale, + output_act_quant_scale=self.output_act_quant_scale, + block_size=block_size, + mm_config=self.mm_config, + act_quant_kwargs=self.act_quant_kwargs, + kernel_preference=self.kernel_preference, + dtype=self.dtype, + output_act_quant_kwargs=self.output_act_quant_kwargs, + ) + return return_and_correct_aliasing(func, args, kwargs, new) + + +@implements(aten.squeeze.dim) +def _(func, types, args, kwargs): + self, dim = args + assert dim == 0, f"Only dim == 0 is supported, got: {dim}" + qdata = self.qdata.squeeze(dim=dim) + scale = self.scale.squeeze(dim=dim) + block_size = [] + for i in range(len(qdata.shape)): + block_size.append(qdata.shape[i] // scale.shape[i]) + + new = self.__class__( + qdata, + scale, + act_quant_scale=self.act_quant_scale, + output_act_quant_scale=self.output_act_quant_scale, + block_size=block_size, + mm_config=self.mm_config, + act_quant_kwargs=self.act_quant_kwargs, + kernel_preference=self.kernel_preference, + dtype=self.dtype, + output_act_quant_kwargs=self.output_act_quant_kwargs, + ) + return return_and_correct_aliasing(func, args, kwargs, new) + + +@implements(aten.select.int) +def _(func, types, args, kwargs): + old_float8_tensor, dim, index = args + assert dim == 0, ( + f"PrototypeFloat8Tensor aten.select.int with {dim=} is not yet supported" + ) + assert len(old_float8_tensor.qdata.shape) == len(old_float8_tensor.scale.shape), ( + "unsupported" + ) + assert len(old_float8_tensor.qdata.shape) == len(old_float8_tensor.block_size), ( + "unsupported" + ) + new_float8_tensor = old_float8_tensor.__class__( + old_float8_tensor.qdata[index], + old_float8_tensor.scale[index], + act_quant_scale=old_float8_tensor.act_quant_scale, + output_act_quant_scale=old_float8_tensor.output_act_quant_scale, + block_size=old_float8_tensor.block_size[1:], + mm_config=old_float8_tensor.mm_config, + act_quant_kwargs=old_float8_tensor.act_quant_kwargs, + kernel_preference=old_float8_tensor.kernel_preference, + dtype=old_float8_tensor.dtype, + output_act_quant_kwargs=old_float8_tensor.output_act_quant_kwargs, + ) + return return_and_correct_aliasing(func, args, kwargs, new_float8_tensor) + + +@implements(aten.unsqueeze.default) +def _(func, types, args, kwargs): + self, dim = args + qdata = self.qdata.unsqueeze(dim=dim) + scale = self.scale.unsqueeze(dim=dim) + block_size = [] + for i in range(len(qdata.shape)): + block_size.append(qdata.shape[i] // scale.shape[i]) + + new = self.__class__( + qdata, + scale, + act_quant_scale=self.act_quant_scale, + output_act_quant_scale=self.output_act_quant_scale, + block_size=block_size, + mm_config=self.mm_config, + act_quant_kwargs=self.act_quant_kwargs, + kernel_preference=self.kernel_preference, + dtype=self.dtype, + output_act_quant_kwargs=self.output_act_quant_kwargs, + ) + return return_and_correct_aliasing(func, args, kwargs, new) + + +@implements(aten.t.default) +def _(func, types, args, kwargs): + assert len(args) == 1 + self = args[0] + assert len(self.block_size) == 2 + new_tensor = self.__class__( + self.qdata.t(), + self.scale.t(), + act_quant_scale=self.act_quant_scale, + output_act_quant_scale=self.output_act_quant_scale, + block_size=(self.block_size[1], self.block_size[0]), + mm_config=self.mm_config, + act_quant_kwargs=self.act_quant_kwargs, + kernel_preference=self.kernel_preference, + dtype=self.dtype, + output_act_quant_kwargs=self.output_act_quant_kwargs, + ) + return return_and_correct_aliasing(func, args, kwargs, new_tensor) + + +@implements_torch_function(torch.Tensor.t) +def _(func, types, args, kwargs): + assert len(args) == 1 + self = args[0] + assert len(self.block_size) == 2 + new_tensor = self.__class__( + self.qdata.t(), + self.scale.t(), + act_quant_scale=self.act_quant_scale, + output_act_quant_scale=self.output_act_quant_scale, + block_size=(self.block_size[1], self.block_size[0]), + mm_config=self.mm_config, + act_quant_kwargs=self.act_quant_kwargs, + kernel_preference=self.kernel_preference, + dtype=self.dtype, + output_act_quant_kwargs=self.output_act_quant_kwargs, + ) + return new_tensor + + +@implements(aten.split.Tensor) +def _(func, types, args, kwargs): + tensor, split_size_or_sections, dim = args + assert isinstance(split_size_or_sections, int), "unimplemented" + + # 2D case + # + # orig + # qdata.shape [M, K] + # scale.shape [M, 1] + # block_size [1, K] + # + # split with size (K // 2) across dim -1: + # qdata.shape [M, K // 2], [M, K // 2] + # scale.shape [M, 1], [M, 1] + # block_size [1, K // 2], [1, K // 2] + # + # split with size (M // 2) across dim 0: + # qdata.shape [M // 2, K], [M // 2, K] + # scale.shape [M // 2, 1], [M // 2, 1] + # block_size [1, K], [1, K] + + # split the qdata + new_qdatas = func(tensor.qdata, split_size_or_sections, dim) + num_chunks = len(new_qdatas) + + # split the scale + new_scales = [] + new_block_sizes = [] + if tensor.scale.shape[dim] == 1 and tensor.block_size[dim] == tensor.shape[dim]: + # repeat the scale, split block_size + for _ in range(num_chunks): + new_scales.append(tensor.scale) + new_block_size = tensor.block_size + new_block_size[dim] = new_block_size[dim] // split_size_or_sections + new_block_sizes.append(new_block_size) + + elif tensor.scale.shape[dim] == tensor.shape[dim] and tensor.block_size[dim] == 1: + # repeat the block size, split scale + new_scales = func(tensor.scale, split_size_or_sections, dim) + for _ in range(num_chunks): + new_block_sizes.append(tensor.block_size) + + else: + raise AssertionError( + f"`aten.split.Tensor` with {dim=} and {tensor.scale.shape=} is not yet implemented" + ) + + new_tensors_list = [] + for idx in range(num_chunks): + new_tensor = tensor.__class__( + new_qdatas[idx], + new_scales[idx], + act_quant_scale=tensor.act_quant_scale, + output_act_quant_scale=tensor.output_act_quant_scale, + block_size=new_block_sizes[idx], + mm_config=tensor.mm_config, + act_quant_kwargs=tensor.act_quant_kwargs, + kernel_preference=tensor.kernel_preference, + dtype=tensor.dtype, + output_act_quant_kwargs=tensor.output_act_quant_kwargs, + ) + new_tensor = return_and_correct_aliasing(func, args, kwargs, new_tensor) + new_tensors_list.append(new_tensor) + + new_tensors_tuple = tuple(new_tensors_list) + return new_tensors_tuple + + +def _choose_quant_func_and_quantize_tensor( + tensor: torch.Tensor, + quant_kwargs: QuantizeTensorKwargs, + act_quant_scale: Optional[torch.Tensor] = None, +) -> torch.Tensor: + if isinstance(quant_kwargs, QuantizeTensorToFloat8Kwargs): + return PrototypeFloat8Tensor.from_hp( + tensor, + quant_kwargs.float8_dtype, + quant_kwargs.granularity, + quant_kwargs.mm_config, + quant_kwargs.hp_value_lb, + quant_kwargs.hp_value_ub, + quant_kwargs.kernel_preference, + scale=act_quant_scale, + ) + raise NotImplementedError(f"Quant kwargs not supported: {quant_kwargs}") + + +# Allow a model with PrototypeFloat8Tensor weights to be loaded with `weights_only=True` +torch.serialization.add_safe_globals([PrototypeFloat8Tensor]) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/gguf/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/gguf/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3e43e1f3dce547bbbf0f6e04f27e3a0a1eab3509 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/gguf/__init__.py @@ -0,0 +1,9 @@ +from .api import GGUFWeightOnlyConfig +from .gguf_quantized_tensor import ( + GGUFQuantizedTensor, +) + +__all__ = [ + "GGUFQuantizedTensor", + "GGUFWeightOnlyConfig", +] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/gguf/api.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/gguf/api.py new file mode 100644 index 0000000000000000000000000000000000000000..bc4b46992ad72f8808f3e68d79fc564e49810778 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/gguf/api.py @@ -0,0 +1,52 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +from dataclasses import dataclass + +import torch + +from torchao.core.config import AOBaseConfig +from torchao.quantization.transform_module import register_quantize_module_handler + +from .gguf_quantized_tensor import GGUFQuantizedTensor + +__all__ = [ + "GGUFWeightOnlyConfig", +] + + +@dataclass +class GGUFWeightOnlyConfig(AOBaseConfig): + dtype: torch.dtype = torch.uint4 + n_blocks_per_superblock: int = 8 + + +@register_quantize_module_handler(GGUFWeightOnlyConfig) +def _gguf_weight_only_transform( + module: torch.nn.Module, + config: GGUFWeightOnlyConfig, +): + """ + Applies gguf weight-only quantization to linear layers. + + Args: + dtype: torch.uint1 to torch.uint8, torch.int32 supported. + n_blocks_per_superblock: the number of super blocks in a 256 element block for gguf, e.g. when it is 8 + it means we have blocks of 32 and 8 blocks in a superblock of 256 elements. + Returns: + Callable for quantization transformation. + """ + weight = module.weight + if (weight.ndim != 2) or (weight.shape[-1] % 256 != 0): + return module + + quantized_weight = GGUFQuantizedTensor.from_float( + weight, + n_blocks_per_superblock=config.n_blocks_per_superblock, + target_dtype=config.dtype, + ) + module.weight = torch.nn.Parameter(quantized_weight, requires_grad=False) + return module diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/gguf/gguf_quantized_tensor.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/gguf/gguf_quantized_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..369afaa049ef01de6b8495f3b8b56abf8dda82ff --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/gguf/gguf_quantized_tensor.py @@ -0,0 +1,270 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +from typing import Optional + +import torch +from torch.utils._python_dispatch import return_and_correct_aliasing + +from torchao.quantization.quant_primitives import ( + _choose_qparams_gguf, + _dequantize_gguf, + _quantize_gguf, +) +from torchao.utils import TorchAOBaseTensor + +_QK_K = 256 +aten = torch.ops.aten + +__all__ = [ + "GGUFQuantizedTensor", +] + + +class GGUFQuantizedTensor(TorchAOBaseTensor): + """ + A Tensor subclass that when applied to a weight used in a linear op/module, + changes that linear op to a weight-only int4 quantized linear op with groupwise + affine quantization on the weight. + """ + + @staticmethod + def __new__( + cls, + n_blocks_per_superblock, + super_block_scale_scale, + super_block_min_scale, + quantized_block_scale, + quantized_block_min, + int_data, + shape, + **kwargs, + ): + kwargs["device"] = kwargs.get("device", super_block_scale_scale.device) + kwargs["dtype"] = kwargs.get("dtype", super_block_scale_scale.dtype) + kwargs["requires_grad"] = False + return torch.Tensor._make_wrapper_subclass(cls, shape, **kwargs) # type: ignore[attr-defined] + + def __init__( + self, + n_blocks_per_superblock, + super_block_scale_scale, + super_block_min_scale, + quantized_block_scale, + quantized_block_min, + int_data, + shape, + **kwargs, + ): + self.n_blocks_per_superblock = n_blocks_per_superblock + self.super_block_scale_scale = super_block_scale_scale + self.super_block_min_scale = super_block_min_scale + self.quantized_block_scale = quantized_block_scale + self.quantized_block_min = quantized_block_min + self.int_data = int_data + + def _apply_fn_to_data(self, fn): + return self.__class__( + self.n_blocks_per_superblock, + fn(self.super_block_scale_scale), + fn(self.super_block_min_sclae), + fn(self.quantized_block_scale), + fn(self.quantized_block_min), + fn(self.int_data), + self.shape, + dtype=self.dtype, + ) + + def __tensor_flatten__(self): + return [ + "super_block_scale_scale", + "super_block_min_scale", + "quantized_block_scale", + "quantized_block_min", + "int_data", + ], ( + self.n_blocks_per_superblock, + self.dtype, + self.shape, + ) + + @classmethod + def __tensor_unflatten__( + cls, tensor_data_dict, attributes, outer_size=None, outer_stride=None + ): + ( + super_block_scale_scale, + super_block_min_scale, + quantized_block_scale, + quantized_block_min, + int_data, + ) = ( + tensor_data_dict["super_block_scale_scale"], + tensor_data_dict["super_block_min_scale"], + tensor_data_dict["quantized_block_scale"], + tensor_data_dict["quantized_block_min"], + tensor_data_dict["int_data"], + ) + n_blocks_per_superblock, dtype, shape = attributes + return cls( + n_blocks_per_superblock, + super_block_scale_scale, + super_block_min_scale, + quantized_block_scale, + quantized_block_min, + int_data, + shape if outer_size is None else outer_size, + dtype=dtype, + ) + + def dequantize(self, output_dtype: Optional[torch.dtype] = None) -> torch.Tensor: + if output_dtype is None: + output_dtype = self.dtype + + block_size = tuple( + [1] * (self.int_data.ndim - 1) + [_QK_K // self.n_blocks_per_superblock] + ) + return _dequantize_gguf( + self.int_data, + block_size, + self.dtype, + self.super_block_scale_scale, + self.super_block_min_scale, + self.quantized_block_scale, + self.quantized_block_min, + output_dtype=output_dtype, + ) + + def to(self, *args, **kwargs): + kwargs = self._get_to_kwargs(*args, **kwargs) + device = kwargs.pop("device") + return self.__class__( + self.n_blocks_per_superblock, + self.super_block_scale_scale.to(device), + self.super_block_min_scale.to(device), + self.quantized_block_scale.to(device), + self.quantized_block_min.to(device), + self.int_data.to(device), + self.shape, + **kwargs, + ) + + def _apply_fn_to_data(self, fn): + """ + Returns a new `CodebookQuantizedTensor`. + """ + return self.__class__( + self.n_blocks_per_superblock, + fn(self.super_block_scale_scale), + fn(self.super_block_min_scale), + fn(self.quantized_block_scale), + fn(self.quantized_block_min), + fn(self.int_data), + self.shape, + dtype=self.dtype, + ) + + def requires_grad_(self, requires_grad=False): + """ + Modifies the tensor's `requires_grad` status in-place. + """ + assert not requires_grad, "Only requires_grad == False is supported" + return self + + @classmethod + def from_float(cls, input_float, n_blocks_per_superblock, target_dtype): + """ + Method used to convert a linear weight tensor to an instance of the + GGMLInt4LinearWeight subclass. + + Example usage:: + + model.lin_mod.weight = ( + GGMLInt4LinearWeight.from_float(model.lin_mod.weight) + ) + """ + assert target_dtype == torch.uint4, ( + "only uint4 quantization is supported right now" + ) + block_size = (1, _QK_K // n_blocks_per_superblock) + ( + super_block_scale_scale, + super_block_min_scale, + quantized_block_scale, + quantized_block_min, + ) = _choose_qparams_gguf(input_float, block_size, target_dtype) + + int_data = _quantize_gguf( + input_float, + block_size, + target_dtype, + super_block_scale_scale, + super_block_min_scale, + quantized_block_scale, + quantized_block_min, + ) + return cls( + n_blocks_per_superblock, + super_block_scale_scale, + super_block_min_scale, + quantized_block_scale, + quantized_block_min, + int_data, + input_float.shape, + ) + + +implements = GGUFQuantizedTensor.implements +implements_torch_function = GGUFQuantizedTensor.implements_torch_function + + +@implements([aten.detach.default, aten.alias.default]) +def _(func, types, args, kwargs): + return return_and_correct_aliasing( + func, args, kwargs, args[0]._apply_fn_to_data(torch.detach) + ) + + +@implements(aten.clone.default) +def _(func, types, args, kwargs): + return return_and_correct_aliasing( + func, args, kwargs, args[0]._apply_fn_to_data(torch.clone) + ) + + +@implements(aten._to_copy.default) +def _(func, types, args, kwargs): + return return_and_correct_aliasing( + func, + args, + kwargs, + args[0].to(*args[1:], **kwargs)._apply_fn_to_data(torch.clone), + ) + + +@implements(aten.linear.default) +@implements_torch_function(torch.nn.functional.linear) +def _(func, types, args, kwargs): + input_tensor, weight_tensor, bias = ( + args[0], + args[1], + args[2] if len(args) > 2 else None, + ) + if not input_tensor.is_floating_point(): + raise NotImplementedError( + f"{func} is not implemented for non floating point input" + ) + + dtype = input_tensor.dtype + + if hasattr(weight_tensor, "dequantize"): + weight_tensor = weight_tensor.dequantize(output_dtype=dtype) + + return torch.nn.functional.linear(input_tensor, weight_tensor, bias) + + +# Allow a model with GGUFQuantizedTensor weights to be loaded with `weights_only=True` +torch.serialization.add_safe_globals([GGUFQuantizedTensor]) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/int4/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/int4/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9fd1756cfae01fb1121906d51654219bda28b7d7 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/int4/__init__.py @@ -0,0 +1,11 @@ +from .inference_workflow import ( + Int4WeightOnlyOpaqueTensorConfig, + Int8DynamicActivationInt4WeightConfig, +) +from .int4_opaque_tensor import Int4OpaqueTensor + +__all__ = [ + "Int4OpaqueTensor", + "Int4WeightOnlyOpaqueTensorConfig", + "Int8DynamicActivationInt4WeightConfig", +] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/int4/inference_workflow.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/int4/inference_workflow.py new file mode 100644 index 0000000000000000000000000000000000000000..e2221d4629868924fff8bbf1a7a45ae399f46498 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/int4/inference_workflow.py @@ -0,0 +1,163 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +import logging +import types +from dataclasses import dataclass + +import torch + +import torchao +from torchao.core.config import AOBaseConfig + +logger = logging.getLogger(__name__) + +from torchao.quantization.quant_api import _linear_extra_repr +from torchao.quantization.quant_primitives import MappingType +from torchao.quantization.quantize_.workflows import ( + Int4ChooseQParamsAlgorithm, +) +from torchao.quantization.transform_module import ( + register_quantize_module_handler, +) + +from .int4_opaque_tensor import Int4OpaqueTensor + + +@dataclass +class Int4WeightOnlyOpaqueTensorConfig(AOBaseConfig): + """ + Configuration for int4 weight only quantization, only groupwise quantization is supported right now. + + Args: + `group_size`: parameter for quantization, controls the granularity of quantization, smaller size is more fine grained, choices are [256, 128, 64, 32] + `int4_choose_qparams_algorithm`: variants of choose qparams algorithm to use for int4, currently support TINYGEMM ("tinygemm") and HQQ ("hqq") + `set_inductor_config`: if True, adjusts `torchinductor` settings to recommended values + """ + + group_size: int = 128 + int4_choose_qparams_algorithm: Int4ChooseQParamsAlgorithm = ( + Int4ChooseQParamsAlgorithm.TINYGEMM + ) + set_inductor_config: bool = True + + def __post_init__(self): + torch._C._log_api_usage_once( + "torchao.prototype.quantization.int4.Int4WeightOnlyOpaqueTensorConfig" + ) + + +def _int4_weight_only_opaque_tensor_quantize(weight, config): + group_size = config.group_size + int4_choose_qparams_algorithm = config.int4_choose_qparams_algorithm + + if weight.shape[-1] % group_size != 0: + logger.info( + f"Skipping quantizing weight with int4 weight only quantization because the shape of weight {weight.shape} is not compatible with group_size {group_size}" + ) + return weight + + block_size = tuple([1 for _ in range(weight.ndim - 1)] + [group_size]) + + block_size = list(block_size) + + new_weight = Int4OpaqueTensor.from_hp( + weight, + block_size, + int4_choose_qparams_algorithm=int4_choose_qparams_algorithm, + ) + return new_weight + + +@register_quantize_module_handler(Int4WeightOnlyOpaqueTensorConfig) +def _int4_weight_only_transform( + module: torch.nn.Module, config: Int4WeightOnlyOpaqueTensorConfig +) -> torch.nn.Module: + if config.set_inductor_config: + torchao.quantization.utils.recommended_inductor_config_setter() + + assert hasattr(module, "weight"), ( + "applying int4 weight only quant requires module to have weight attribute" + + " but {module} does not have one" + ) + new_weight = _int4_weight_only_opaque_tensor_quantize(module.weight, config) + module.weight = torch.nn.Parameter(new_weight, requires_grad=False) + module.extra_repr = types.MethodType(_linear_extra_repr, module) + return module + + +@dataclass +class Int8DynamicActivationInt4WeightConfig(AOBaseConfig): + """ + Configuration for int8 dynamic activation + int4 weight quantization on CPU, + using Int4OpaqueTensor (tensor subclassing) with the da8w4_linear_cpu backend. + + Weights are quantized per-group (asymmetric int4) and prepacked at quantization time. + Activations are quantized dynamically per-token at runtime. + + Args: + `group_size`: quantization group size for weights; K must be divisible by group_size; + choices are [128, 64, 32]; otherwise weight will not be quantized + `act_mapping_type`: activation quantization type: + - MappingType.ASYMMETRIC (default): uint8 activation quantization + - MappingType.SYMMETRIC: int8 activation quantization (requires PyTorch >= 2.8) + `set_inductor_config`: if True, adjusts `torchinductor` settings to recommended values + Example: + + .. literalinclude:: ../../examples/prototype/int8_dynamic_activation_int4_weight.py + :language: python + """ + + group_size: int = 32 + act_mapping_type: MappingType = MappingType.ASYMMETRIC + set_inductor_config: bool = True + + def __post_init__(self): + torch._C._log_api_usage_once( + "torchao.prototype.quantization.int4.Int8DynamicActivationInt4WeightConfig" + ) + + +@register_quantize_module_handler(Int8DynamicActivationInt4WeightConfig) +def _int8_dynamic_act_int4_weight_transform( + module: torch.nn.Module, config: Int8DynamicActivationInt4WeightConfig +) -> torch.nn.Module: + if config.set_inductor_config: + torchao.quantization.utils.recommended_inductor_config_setter() + + assert hasattr(module, "weight"), ( + "applying DA8W4 quant requires module to have weight attribute" + + f" but {module} does not have one" + ) + assert "CPU" in torch._C._dispatch_dump("torchao::da8w4_linear_cpu"), ( + "DA8W4 on CPU requires the da8w4_linear_cpu kernel to be built and available" + ) + weight = module.weight + if weight.shape[-1] % config.group_size != 0 or config.group_size not in [ + 128, + 64, + 32, + ]: + logger.info( + f"Skipping DA8W4 quantization: weight shape {weight.shape} is not compatible " + f"with group_size {config.group_size} (must be divisible and one of [128, 64, 32])" + ) + return module + if weight.shape[0] % 32 != 0 or weight.shape[-1] % 2 != 0: + logger.info( + f"Skipping DA8W4 quantization: weight shape {weight.shape} requires " + "N divisible by 32 and K divisible by 2" + ) + return module + + new_weight = Int4OpaqueTensor.from_hp_da8w4( + weight, + group_size=config.group_size, + act_mapping_type=config.act_mapping_type, + ) + module.weight = torch.nn.Parameter(new_weight, requires_grad=False) + module.extra_repr = types.MethodType(_linear_extra_repr, module) + return module diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/int4/int4_opaque_tensor.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/int4/int4_opaque_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..bde691dd782be24f02da12493aae6b4f9a403ffe --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/int4/int4_opaque_tensor.py @@ -0,0 +1,441 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + + +import math +from typing import List, Optional + +import torch + +from torchao.quantization.quant_primitives import ( + MappingType, + _choose_qparams_affine_tinygemm, + _choose_qparams_and_quantize_affine_hqq, + _quantize_affine_tinygemm, + choose_qparams_affine, + quantize_affine, +) +from torchao.quantization.quantize_.workflows import ( + Int4ChooseQParamsAlgorithm, +) +from torchao.quantization.utils import ( + _get_per_token_block_size, + pack_tinygemm_scales_and_zeros, +) +from torchao.utils import ( + TorchAOBaseTensor, + torch_version_at_least, +) + +__all__ = [ + "Int4OpaqueTensor", +] + +aten = torch.ops.aten + + +class Int4OpaqueTensor(TorchAOBaseTensor): + """ + int4 weight quantization on CPU with two supported paths: + + 1. A16W4 (weight-only): float16/bfloat16/float32 activation + int4 weight, + using tinygemm kernel (_weight_int4pack_mm_for_cpu). + + 2. DA8W4 (dynamic activation): int8 dynamic activation + int4 weight, + using da8w4 kernel (da8w4_linear_cpu). Activation is quantized + per-token dynamically at runtime. + + The path is selected based on `act_mapping_type`: + - None → A16W4 tinygemm path + - "asymmetric" or "symmetric" → DA8W4 path + + Mandatory Tensor Attributes (A16W4): + qdata: packed int4 weight. + A16W4: preshuffled for tinygemm, shape (N, K/2) + DA8W4: prepacked for da8w4_linear_cpu (4D) + scale_and_zero: weight quantization params. + A16W4: packed scales+zeros for tinygemm, shape (K/group_size, N, 2) + DA8W4: packed scales, shape (N/block_n, G, block_n) + + Mandatory Non-Tensor Attributes: + block_size: quantization block size, e.g. [1, group_size] + shape: original weight shape [N, K] + + Optional Tensor Data Attributes: + act_pre_scale: activation pre-scale (A16W4 only) + qzeros: packed weight zero-points for DA8W4, shape (N/block_n, G, block_n) + compensation: weight compensation for DA8W4, shape (N/block_n, K/block_k, block_n) + + Optional Non-Tensor Attributes: + act_mapping_type: None for A16W4; "asymmetric" or "symmetric" for DA8W4 + """ + + tensor_data_names = ["qdata", "scale_and_zero"] + tensor_attribute_names = ["block_size", "shape"] + optional_tensor_data_names = ["act_pre_scale", "qzeros", "compensation"] + optional_tensor_attribute_names = ["act_mapping_type"] + + def __new__( + cls, + qdata, + scale_and_zero, + block_size, + shape, + act_pre_scale: Optional[torch.Tensor] = None, + qzeros: Optional[torch.Tensor] = None, + compensation: Optional[torch.Tensor] = None, + act_mapping_type: Optional[str] = None, + ): + kwargs = {} + kwargs["device"] = qdata.device + kwargs["dtype"] = scale_and_zero.dtype + kwargs["requires_grad"] = False + return torch.Tensor._make_wrapper_subclass(cls, shape, **kwargs) # type: ignore[attr-defined] + + def __init__( + self, + qdata: torch.Tensor, + scale_and_zero: torch.Tensor, + block_size: List[int], + shape: torch.Size, + act_pre_scale: Optional[torch.Tensor] = None, + qzeros: Optional[torch.Tensor] = None, + compensation: Optional[torch.Tensor] = None, + act_mapping_type: Optional[str] = None, + ): + super().__init__() + self.qdata = qdata + self.scale_and_zero = scale_and_zero + self.block_size = block_size + self.act_pre_scale = act_pre_scale + self.qzeros = qzeros + self.compensation = compensation + self.act_mapping_type = act_mapping_type + + def _quantization_type(self): + if self.act_mapping_type is not None: + s = f"da8w4, shape={self.shape}, block_size={self.block_size}, act={self.act_mapping_type}, device={self.device}" + else: + s = f"shape={self.shape}, block_size={self.block_size}, device={self.device}" + if self.act_pre_scale is not None: + s += f", act_pre_scale.shape={self.act_pre_scale.shape}" + return s + + @classmethod + def from_hp( + cls, + w: torch.Tensor, + block_size: List[int], + int4_choose_qparams_algorithm: Int4ChooseQParamsAlgorithm = Int4ChooseQParamsAlgorithm.TINYGEMM, + ): + assert w.ndim == 2 and w.device.type == "cpu", ( + f"Expecting 2D tensor on CPU, but got: {w.shape} on {w.device.type}" + ) + assert len(block_size) == w.ndim + assert block_size[0] == 1 and block_size[1] in (32, 64, 128), ( + f"Expecting groupwise quantization with group size = 32/64/128, but got block_size: {block_size}" + ) + original_shape = w.shape + mapping_type = MappingType.ASYMMETRIC + target_dtype = torch.int32 + quant_min = 0 + quant_max = 15 + eps = 1e-6 + scale_dtype = None + zero_point_dtype = w.dtype + + # we support two paths for constructing a Int4OpaqueTensor + # 1. use [hqq](https://mobiusml.github.io/hqq_blog/) algorithm to compute + # scale and zero_point, then convert to the format that's compatible with tinygemm kernels + # 2. don't use hqq, use default tinygemm algorithm to compute scale and zero_point + # + # both approach should have the same performance since both are using CPU tinygemm kernel for gemm + # 1. typically will have higher accuracy compared to 2. + if int4_choose_qparams_algorithm == Int4ChooseQParamsAlgorithm.HQQ: + nbits = int(math.log2(quant_max + 1)) + axis = 1 + group_size = block_size[-1] + int_data, scale, zero_point, _ = _choose_qparams_and_quantize_affine_hqq( + w, + nbits=nbits, + group_size=group_size, + axis=axis, + compute_dtype=zero_point_dtype, + device=w.device, + ) + int_data = int_data.to(target_dtype) + else: + assert ( + int4_choose_qparams_algorithm == Int4ChooseQParamsAlgorithm.TINYGEMM + ), ( + f"Unsupported Int4ChooseQParamsAlgorithm: {int4_choose_qparams_algorithm}" + ) + + scale, zero_point = _choose_qparams_affine_tinygemm( + w, + mapping_type, + block_size, + target_dtype, + quant_min, + quant_max, + eps, + scale_dtype, + zero_point_dtype, + ) + int_data = _quantize_affine_tinygemm( + w, + block_size, + scale, + zero_point, + target_dtype, + quant_min, + quant_max, + ) + assert int_data.dtype == torch.int32, ( + "torch.ops.aten._convert_weight_to_int4pack_for_cpu expects `int32` dtype" + ) + packed_weight = torch.ops.aten._convert_weight_to_int4pack_for_cpu( + int_data, + 1, # innerKTiles is not needed for CPU + ) + + scale = scale.reshape(int_data.shape[0], -1) + zero_point = zero_point.reshape(int_data.shape[0], -1) + + scale_and_zero = pack_tinygemm_scales_and_zeros(scale, zero_point, scale.dtype) + return Int4OpaqueTensor( + qdata=packed_weight, + scale_and_zero=scale_and_zero, + block_size=block_size, + shape=original_shape, + act_pre_scale=None, + ) + + @classmethod + def from_hp_da8w4( + cls, + w: torch.Tensor, + group_size: int = 32, + act_mapping_type: MappingType = MappingType.ASYMMETRIC, + ): + """ + Quantize a float weight tensor for DA8W4 (int8 dynamic activation + int4 weight) on CPU. + + The weight is quantized per-group (asymmetric int4), then prepacked via + torch.ops.torchao.da8w4_linear_prepack_cpu for the CPU kernel. + + Args: + w: float weight tensor, shape [N, K], must be on CPU + group_size: quantization group size, K must be divisible by group_size + act_mapping_type: MappingType.ASYMMETRIC (uint8 activation, default) or + MappingType.SYMMETRIC (int8 activation, requires PyTorch >= 2.8) + """ + assert w.ndim == 2 and w.device.type == "cpu", ( + f"Expecting 2D tensor on CPU, but got: {w.shape} on {w.device.type}" + ) + assert group_size in (32, 64, 128), ( + f"Expecting group_size to be 32/64/128, but got: {group_size}" + ) + assert w.shape[1] % group_size == 0, ( + f"K={w.shape[1]} must be divisible by group_size={group_size}" + ) + assert w.shape[0] % 32 == 0 and w.shape[1] % 2 == 0, ( + f"N={w.shape[0]} must be divisible by 32 and K={w.shape[1]} must be even for DA8W4" + ) + original_shape = w.shape + block_size = [1, group_size] + + # Quantize weight: asymmetric int4 per-group → uint8 [N, K], values in [0, 15] + scale, zero_point = choose_qparams_affine( + w, + MappingType.ASYMMETRIC, + block_size, + torch.uint8, + quant_min=0, + quant_max=15, + eps=1e-6, + scale_dtype=torch.float32, + zero_point_dtype=torch.int32, + ) + int4_weight = quantize_affine( + w, + block_size, + scale, + zero_point, + torch.uint8, + quant_min=0, + quant_max=15, + ).to(torch.uint8) + + # Prepack for da8w4_linear_cpu + packed_weight, packed_scales, packed_qzeros, compensation = ( + torch.ops.torchao.da8w4_linear_prepack_cpu( + int4_weight, + scale, + zero_point.to(torch.int8), + ) + ) + + act_str = ( + "symmetric" if act_mapping_type == MappingType.SYMMETRIC else "asymmetric" + ) + return cls( + qdata=packed_weight, + scale_and_zero=packed_scales, + block_size=block_size, + shape=original_shape, + act_pre_scale=None, + qzeros=packed_qzeros, + compensation=compensation, + act_mapping_type=act_str, + ) + + +implements = Int4OpaqueTensor.implements +implements_torch_function = Int4OpaqueTensor.implements_torch_function + + +def _da8w4_linear(input_tensor, weight_tensor, bias): + """DA8W4 linear: dynamically quantize activation per-token, then call da8w4_linear_cpu.""" + orig_act_size = input_tensor.size() + orig_dtype = input_tensor.dtype + + # Reshape activation to 2D + act_fp = input_tensor.reshape(-1, input_tensor.shape[-1]) + per_token_block_size = _get_per_token_block_size(act_fp) + + if weight_tensor.act_mapping_type == "symmetric": + assert torch_version_at_least("2.8.0"), ( + "Symmetric int8 activation quantization requires PyTorch 2.8+" + ) + # Symmetric int8 quantization: values in [-127, 127] + act_scale, act_zero_point = choose_qparams_affine( + act_fp, + MappingType.SYMMETRIC, + per_token_block_size, + torch.int8, + quant_min=-127, + quant_max=127, + eps=torch.finfo(torch.float32).eps, + scale_dtype=torch.float32, + zero_point_dtype=torch.int8, + ) + act_int = quantize_affine( + act_fp, + per_token_block_size, + act_scale, + act_zero_point, + torch.int8, + quant_min=-127, + quant_max=127, + ) + else: + assert torch_version_at_least("2.7.0"), ( + "Asymmetric uint8 activation quantization requires PyTorch 2.7+" + ) + # Asymmetric uint8 quantization: values in [0, 255] + act_scale, act_zero_point = choose_qparams_affine( + act_fp, + MappingType.ASYMMETRIC, + per_token_block_size, + torch.uint8, + quant_min=0, + quant_max=255, + eps=torch.finfo(torch.float32).eps, + scale_dtype=torch.float32, + zero_point_dtype=torch.int32, + ) + act_int = quantize_affine( + act_fp, + per_token_block_size, + act_scale, + act_zero_point, + torch.uint8, + quant_min=0, + quant_max=255, + ) + + act_scale_1d = act_scale.reshape(-1) + act_qzeros_1d = act_zero_point.reshape(-1).to(torch.int32) + + y = torch.ops.torchao.da8w4_linear_cpu.default( + act_int.contiguous(), + act_scale_1d, + act_qzeros_1d, + weight_tensor.qdata, + weight_tensor.scale_and_zero, + weight_tensor.qzeros, + weight_tensor.compensation, + bias.float() if bias is not None else bias, + orig_dtype, + ) + + orig_out_features = weight_tensor.shape[-2] + y = y[:, :orig_out_features] + y = y.reshape(*orig_act_size[:-1], orig_out_features) + return y.to(orig_dtype) + + +@implements(aten.linear.default) +@implements_torch_function(torch.nn.functional.linear) +def _(func, types, args, kwargs): + input_tensor, weight_tensor, bias = ( + args[0], + args[1], + args[2] if len(args) > 2 else None, + ) + assert input_tensor.device.type == "cpu", ( + f"For CPU device only but got: {input_tensor.device}" + ) + assert isinstance(weight_tensor, Int4OpaqueTensor), ( + f"Expected weight_tensor to be Int4OpaqueTensor, got: {type(weight_tensor)}" + ) + assert weight_tensor.block_size[0] == 1, ( + f"Requires groupwise quantization, got block_size: {weight_tensor.block_size}" + ) + assert input_tensor.shape[-1] == weight_tensor.shape[1], ( + f"Shapes of input and weight do not match, input:{input_tensor.shape}, weight: {weight_tensor.shape}" + ) + + # DA8W4 path: dynamic int8 activation + int4 weight + if weight_tensor.act_mapping_type is not None: + return _da8w4_linear(input_tensor, weight_tensor, bias) + + # A16W4 path: float activation + int4 weight (tinygemm) + if weight_tensor.act_pre_scale is not None: + input_tensor = input_tensor * weight_tensor.act_pre_scale + + act_mat = input_tensor + packed_weight = weight_tensor.qdata + scale_and_zero = weight_tensor.scale_and_zero + + orig_act_size = act_mat.size() + orig_dtype = act_mat.dtype + + # reshape to 2D + act_mat = act_mat.reshape(-1, act_mat.shape[-1]) + + # groupwise int4 quantization + groupsize = weight_tensor.block_size[1] + y = torch.ops.aten._weight_int4pack_mm_for_cpu( + act_mat.contiguous(), packed_weight, groupsize, scale_and_zero + ) + + # remove out_feature padding + assert weight_tensor.ndim == 2 + orig_out_features = weight_tensor.shape[-2] + y = y[:, :orig_out_features] + y = y.reshape(*orig_act_size[:-1], orig_out_features) + + if bias is not None: + y += bias + return y.to(orig_dtype) + + +Int4OpaqueTensor.__module__ = "torchao.prototype.quantization.int4" + +# Allow a model with Int4OpaqueTensor weights to be loaded with `weights_only=True` +torch.serialization.add_safe_globals([Int4OpaqueTensor]) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/int8_lut_tensor/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/int8_lut_tensor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dd538681824d43b95498184b0ba65053b611fc3a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/int8_lut_tensor/__init__.py @@ -0,0 +1,5 @@ +from .int8_lut_tensor import Int8LutTensor + +__all__ = [ + "Int8LutTensor", +] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/int8_lut_tensor/int8_lut_tensor.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/int8_lut_tensor/int8_lut_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..24c45a08b57b2d85d705e0e30bfe92b4805a4543 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/int8_lut_tensor/int8_lut_tensor.py @@ -0,0 +1,243 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. +from typing import Optional + +import torch + +from torchao.quantization.quant_primitives import ( + _DTYPE_TO_BIT_WIDTH, + _DTYPE_TO_QVALUE_BOUNDS, +) +from torchao.quantization.quantize_.workflows.intx.intx_opaque_tensor import ( + _is_kernel_library_loaded, +) +from torchao.quantization.quantize_.workflows.intx.intx_unpacked_to_int8_tensor import ( + IntxUnpackedToInt8Tensor, + IntxUnpackedToInt8TensorActivationQuantization, +) +from torchao.utils import TorchAOBaseTensor + +aten = torch.ops.aten + + +class Int8LutTensor(TorchAOBaseTensor): + """ + Tensor subclass that does int8 dynamic activation quantization with lookup table quantization + """ + + tensor_data_names = ["packed_weights"] + tensor_attribute_names = [ + "bit_width", + "block_size", + "shape", + "dtype", + "packed_weights_has_bias", + ] + + def __new__( + cls, + packed_weights, + bit_width, + block_size, + shape, + dtype, + packed_weights_has_bias, + ): + kwargs = {} + kwargs["device"] = packed_weights.device + kwargs["dtype"] = dtype + kwargs["requires_grad"] = False + return torch.Tensor._make_wrapper_subclass(cls, shape, **kwargs) # type: ignore[attr-defined] + + def __init__( + self, + packed_weights, + bit_width, + block_size, + shape, + dtype, + packed_weights_has_bias, + ): + super().__init__() + assert packed_weights.device == torch.device("cpu") + self.packed_weights = packed_weights + self.bit_width = bit_width + self.block_size = block_size + self.packed_weights_has_bias = packed_weights_has_bias + + def _quantization_type(self): + return f"bit_width={self.bit_width}, block_size={self.block_size}, shape={self.shape}, dtype={self.dtype}, device={self.device}" + + def to(self, *args, **kwargs): + raise NotImplementedError("to() is not implemented for IntxOpaqueTensor") + + @classmethod + def _get_lut_params(cls, tensor: IntxUnpackedToInt8Tensor): + assert isinstance(tensor, IntxUnpackedToInt8Tensor) + assert tensor.target_dtype in [torch.int1, torch.int2, torch.int3, torch.int4] + + qdata = tensor.qdata + scale = tensor.scale + zero_point = tensor.zero_point + + if tensor._has_float_zero_point(): + # Stretched tensors from PARQ should have -0.5 has zero_point + assert torch.all(zero_point == -0.5) + is_stretched_tensor = True + else: + assert torch.all(zero_point == 0) + is_stretched_tensor = False + + quant_min, quant_max = _DTYPE_TO_QVALUE_BOUNDS[tensor.target_dtype] + lut_indices = qdata - quant_min + lut = torch.arange(quant_min, quant_max + 1) + + # Construct LUT as 2 * ([q_min, q_max] - 0.5) + if is_stretched_tensor: + lut = 2 * lut + 1 + scale = 0.5 * scale + + # LUT must be 2D and int8 + lut = lut.reshape(1, -1).to(torch.int8) + + # Scale must be 1D and float32 + scale = scale.reshape(-1).to(torch.float32) + + return lut, lut_indices, scale + + @classmethod + def from_intx_unpacked_to_int8_tensor( + cls, + tensor: IntxUnpackedToInt8Tensor, + *, + bias: Optional[torch.Tensor] = None, + ): + """ + Constructs a Int8LutTensor from an IntxUnpackedToInt8Tensor. + If bias is passed, bias is packed into the tensor. + """ + + assert _is_kernel_library_loaded(), "TorchAO kernel library is not loaded" + assert ( + tensor.activation_quantization + == IntxUnpackedToInt8TensorActivationQuantization.INT8_ASYM_PER_TOKEN + ), ( + "IntxUnpackedToInt8Tensor must have INT8_ASYM_PER_TOKEN activation quantization" + ) + + assert len(tensor.block_size) == 2 + assert tensor.block_size[0] == 1 + scale_group_size = tensor.block_size[1] + + packed_weights_has_bias = bias is not None + if packed_weights_has_bias: + n, k = tensor.shape + assert bias.shape == (n,) + bias = bias.to(torch.float32) + + lut, lut_indices, scale = cls._get_lut_params(tensor) + bit_width = _DTYPE_TO_BIT_WIDTH[tensor.target_dtype] + packed_weights = getattr( + torch.ops.torchao, f"_pack_8bit_act_{bit_width}bit_weight_with_lut" + )( + lut_indices, + lut, + scale, + scale_group_size, + bias, + None, + ) + + block_size = [b for b in tensor.block_size] + shape = tensor.shape + bit_width = _DTYPE_TO_BIT_WIDTH[tensor.target_dtype] + return cls( + packed_weights, + bit_width, + block_size, + shape, + tensor.dtype, + packed_weights_has_bias, + ) + + +implements = Int8LutTensor.implements +implements_torch_function = Int8LutTensor.implements_torch_function + + +def _linear_impl_2d( + input_tensor: torch.Tensor, weight_tensor: torch.Tensor, bias: torch.Tensor +): + assert isinstance(weight_tensor, Int8LutTensor) + assert input_tensor.dim() == 2 + assert weight_tensor.dim() == 2 + assert weight_tensor.block_size[0] == 1 + group_size = weight_tensor.block_size[1] + + m, k = input_tensor.shape + n, k_ = weight_tensor.shape + assert k_ == k + + packed_weights = weight_tensor.packed_weights + bit_width = weight_tensor.bit_width + + if weight_tensor.dtype != torch.float32: + input_tensor = input_tensor.to(torch.float32) + + res = getattr( + torch.ops.torchao, + f"_linear_8bit_act_{bit_width}bit_weight", + )( + input_tensor, + packed_weights, + group_size, + n, + k, + ) + if weight_tensor.dtype != torch.float32: + res = res.to(weight_tensor.dtype) + + return res + + +@implements(aten.linear.default) +@implements_torch_function(torch.nn.functional.linear) +def _(func, types, args, kwargs): + input_tensor, weight_tensor, bias = ( + args[0], + args[1], + args[2] if len(args) > 2 else None, + ) + + # TODO: why was this added https://github.com/pytorch/ao/pull/2043 + if input_tensor.numel() == 0: + return input_tensor + + if input_tensor.dim() == 1: + k = input_tensor.shape[0] + input_tensor = input_tensor.reshape(1, k) + res = _linear_impl_2d(input_tensor, weight_tensor, bias) + res = res.reshape(-1) + elif input_tensor.dim() == 2: + res = _linear_impl_2d(input_tensor, weight_tensor, bias) + else: + assert input_tensor.dim() >= 3 + lead_shape = input_tensor.shape[0:-2] + m, k = input_tensor.shape[-2], input_tensor.shape[-1] + n, k_ = weight_tensor.shape + assert k_ == k + res = _linear_impl_2d(input_tensor.reshape(-1, k), weight_tensor, bias) + res = res.reshape(*lead_shape, m, n) + + if bias is not None: + assert not weight_tensor.packed_weights_has_bias + res = res + bias + + return res + + +# Allow a model with Int8LutTensor weights to be loaded with `weights_only=True` +torch.serialization.add_safe_globals([Int8LutTensor]) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/mixed_precision/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/mixed_precision/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..af62c3899ff6fb1540e28f4ad5be4d59ad0e3f87 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/__init__.py @@ -0,0 +1,21 @@ +from .module_swap import ( + QuantizationRecipe, + quantize_module_swap, +) +from .quantized_modules import ( + QuantizedEmbedding, + QuantizedLinear, +) +from .quantizers import ( + CodeBookQuantizer, + IntQuantizer, +) + +__all__ = [ + "CodeBookQuantizer", + "IntQuantizer", + "QuantizedEmbedding", + "QuantizedLinear", + "QuantizationRecipe", + "quantize_module_swap", +] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d1fe5847b15aa37f05a1b2c74c1a52791910e98 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/__pycache__/module_swap.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/__pycache__/module_swap.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92265d29d0ed3ebf0f7f3744b23a87a69234684e Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/__pycache__/module_swap.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/__pycache__/quantized_modules.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/__pycache__/quantized_modules.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef2d3c1eab7788142ac584de6a9a64ea0c7bca80 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/__pycache__/quantized_modules.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/__pycache__/quantizers.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/__pycache__/quantizers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5abf80dbab6cabf1ba14b7fc941807240acf452e Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/__pycache__/quantizers.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/__pycache__/range_setting_methods.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/__pycache__/range_setting_methods.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5dfa43c7965f7e274efb927ec73cd8cc3c8525bc Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/__pycache__/range_setting_methods.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/__pycache__/utils.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ea0f15d11cbe0d1fa2b07c5bd11e21ae93e7125 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/__pycache__/utils.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/data_getters/llm_ptq_data_getter.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/data_getters/llm_ptq_data_getter.py new file mode 100644 index 0000000000000000000000000000000000000000..476f1876987a62a0b8e14e2b8b2a47951499e794 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/data_getters/llm_ptq_data_getter.py @@ -0,0 +1,133 @@ +from typing import Dict + +import torch +import torch.nn as nn +from transformers.models.llama.modeling_llama import LlamaForCausalLM + +from torchao.prototype.quantization.module_swap.data_getters.ptq_data_getter import ( + DataGetter, + get_module_input_data, +) +from torchao.prototype.quantization.module_swap.utils import ( + get_layer_by_name, +) + + +class LLMPTQDataGetter(DataGetter): + """ + This datagetter can be used to efficiently retrieve layer-wise input data from a LlamaForCausalLM model + The two benefits are + 1) It caches the data in between layer's residuals, so previous layers dont have to be computed + 2) Layers with the same input have their input cached and returned + + Usage is simple, give it a model, and data + then data_getter.pop(model, layer_name) for each batch of data you require + + the actual model passed is used to get the data, so if you want to e.g. quantize + the entire network with weight quantizers, it uses that data + The datagetter has to be called in-order of the layer's occurence in the network, otherwise it will fail + + """ + + def __init__( + self, model: LlamaForCausalLM, data: torch.Tensor, batch_size: int + ) -> None: + super().__init__() + self.initialize(model, data, batch_size) + + def initialize(self, model: nn.Module, data: torch.Tensor, batch_size: int) -> None: + assert isinstance(model, LlamaForCausalLM) + assert isinstance(data, torch.Tensor) + + # set attention_mask and/or position_ids + self.layer_kwargs: Dict[str, torch.Tensor] = self.get_layer_kwargs(model, data) + + self.input_data_cache: torch.Tensor = get_module_input_data( + model, data, model.model.layers[0], batch_size + ) + self.current_layer_idx = 0 + self.previously_called_name: str = "" + self.batch_size = batch_size + self.output_data_cache: torch.Tensor = torch.zeros_like(data) + self.matched_input_layers = [ + ["q_proj", "k_proj", "v_proj"], + ["up_proj", "gate_proj"], + ] + + def pop(self, model: nn.Module, name: str) -> torch.Tensor: + assert isinstance(model, LlamaForCausalLM) + with torch.no_grad(): + # special case for the last layer + if name != "lm_head": + query_layer_idx = int(name.split(".")[2]) + else: + query_layer_idx = len(model.model.layers) + + assert query_layer_idx >= self.current_layer_idx, ( + "pop() called out of order, layers have to be called in order" + ) + + # TODO: batch the next two parts + + # progress the progress over layers + while query_layer_idx > self.current_layer_idx: + self.input_data_cache = model.model.layers[self.current_layer_idx]( + self.input_data_cache, **self.layer_kwargs + )[0] + self.current_layer_idx += 1 + + # special case for the final layer + if name == "lm_head": + return self.input_data_cache + + # use cached output data if the outputs are matching + base_name = self.get_base_name(name) + for matching_list in self.matched_input_layers: + if base_name in matching_list: + previous_base_name = self.get_base_name(self.previously_called_name) + if previous_base_name in matching_list: + self.previously_called_name = name + return self.output_data_cache + + # get data from current requested layer + query_layer = get_layer_by_name(model, name) + layer_output_data = get_module_input_data( + model.model.layers[self.current_layer_idx], + self.input_data_cache, + query_layer, + self.batch_size, + self.layer_kwargs, + ) + + # cache the data for next call + self.output_data_cache = layer_output_data + self.previously_called_name = name + return layer_output_data + + def get_layer_kwargs( + self, model: LlamaForCausalLM, data: torch.Tensor + ) -> Dict[str, torch.Tensor]: + # get used attention_mask and position_ids + layer_kwargs: Dict[str, torch.Tensor] = {} + + class Catcher(nn.Module): + def __init__(self, module): + super().__init__() + self.module = module + + def forward(self, inp, **kwargs): + if kwargs["attention_mask"] is not None: + layer_kwargs["attention_mask"] = kwargs["attention_mask"] + if kwargs["position_ids"] is not None: + layer_kwargs["position_ids"] = kwargs["position_ids"] + raise ValueError + + device = model.parameters().__next__().device + model.model.layers[0] = Catcher(model.model.layers[0]) + try: + model(data[0:2].to(device)) + except ValueError: + pass + model.model.layers[0] = model.model.layers[0].module + + return layer_kwargs diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/data_getters/ptq_data_getter.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/data_getters/ptq_data_getter.py new file mode 100644 index 0000000000000000000000000000000000000000..6f17ebdc490250461a872ecf4c619278bbfc9685 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/data_getters/ptq_data_getter.py @@ -0,0 +1,67 @@ +from typing import Dict, List + +import torch +import torch.nn as nn + + +class ExpectedError(Exception): + pass + + +class DataGetter: + def __init__(self) -> None: + return + + def pop(self, model: nn.Module, name: str) -> torch.Tensor: + raise NotImplementedError() + + def get_base_name(self, name: str) -> str: + base_name = name.split(".")[-1] + if base_name.isnumeric(): + base_name = name.split(".")[-2] + return base_name + + def initialize(self, model: nn.Module, data: torch.Tensor, batch_size: int) -> None: + raise NotImplementedError() + + +def get_module_input_data( + model: nn.Module, + data: torch.Tensor, + module: nn.Module, + batch_size: int, + layer_kwargs: Dict[str, torch.Tensor] = {}, # noqa +) -> torch.Tensor: + with torch.no_grad(): + if isinstance(data, list): + num_data = len(data) + else: + num_data = data.shape[0] + num_batches = num_data // batch_size + assert num_data % batch_size == 0 + + input_data: List[torch.Tensor] = [] + + def _input_data_hook( + module: nn.Module, input: List[torch.Tensor], output: List[torch.Tensor] + ) -> None: + input_data.append(input[0].detach()) + assert len(input) == 1 + raise ExpectedError + + hook = module.register_forward_hook(_input_data_hook) + + for i in range(num_batches): + try: + this_batch = data[i * batch_size : (i + 1) * batch_size] + this_batch = this_batch.to(next(model.parameters()).device) + if layer_kwargs: + model(this_batch, **layer_kwargs) + else: + model(this_batch) + except ExpectedError: + pass + + hook.remove() + return_data = torch.cat(input_data, dim=0) + return return_data diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/module_swap.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/module_swap.py new file mode 100644 index 0000000000000000000000000000000000000000..e56965c8d21f4c616d87ef870ca66feaf5f59b39 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/module_swap.py @@ -0,0 +1,167 @@ +import logging +from dataclasses import dataclass, field +from typing import List, Union + +import torch +import torch.nn as nn + +from torchao.prototype.quantization.module_swap.algorithms import ( + kmeans_codebook, +) +from torchao.prototype.quantization.module_swap.quantized_modules import ( + QuantizedEmbedding, + QuantizedLinear, +) +from torchao.prototype.quantization.module_swap.quantizers import ( + CodeBookQuantizer, + IntQuantizer, +) +from torchao.prototype.quantization.module_swap.range_setting_methods import ( + set_weight_min_max, +) + +logger: logging.Logger = logging.getLogger(__name__) + + +# TODO: express this using AOBaseConfig +@dataclass +class QuantizationRecipe: + # weights + weight_bits: int = 4 + weight_group_size: Union[int, str] = 32 + weight_quantization: bool = True + dynamic_weights: bool = False + + # weight codebooking settings + weight_codebook: bool = False # if we're using weight codebooks + codebook_dim: int = 1 + + # activations + activation_bits: int = 8 + activation_group_size: Union[int, str] = "per_token" + activation_quantization: bool = False + input_quantization: bool = False + output_quantization: bool = False + dynamic_activations: bool = True + + # general + range_learning: bool = False + embedding_quantization: bool = True + embedding_bits: int = 4 + embedding_group_size: Union[int, str] = 32 + exclude_layers: List[str] = field(default_factory=lambda: ["lm_head"]) + + +def get_layer_parent_by_name(model: nn.Module, input_name: str) -> nn.Module: + parent_name = input_name.rsplit(".", 1)[:-1] + if len(parent_name) == 0: # parent is model itself + return model + else: + parent_name = parent_name[0] + + for name, module in model.named_modules(): + if parent_name == name: + return module + raise ValueError(f"Layer {input_name} not found in model") + + +# TODO: delete this, use quantize_ instead +def quantize_module_swap( + model: nn.Module, recipe: QuantizationRecipe, dtype: torch.dtype = torch.float32 +) -> nn.Module: + model = replace_all_linear_with_quantized_linear(model, recipe) + if recipe.embedding_quantization: + model = replace_all_embedding_with_quantized(model, recipe) + initialize_model_parameters(model, recipe, dtype) + return model + + +def replace_all_embedding_with_quantized( + model: nn.Module, recipe: QuantizationRecipe +) -> nn.Module: + for name, module in model.named_modules(): + if isinstance(module, nn.Embedding): + if name in recipe.exclude_layers: + logger.info(f"skip layer {name} in exclude list") + else: + quantized_embedding = QuantizedEmbedding( + num_embeddings=module.num_embeddings, + embedding_dim=module.embedding_dim, + padding_idx=module.padding_idx, + max_norm=module.max_norm, + norm_type=module.norm_type, + scale_grad_by_freq=module.scale_grad_by_freq, + sparse=module.sparse, + _weight=module.weight, + num_bits=recipe.embedding_bits, + group_size=recipe.embedding_group_size, + quantization_mode="symmetric", + range_learning=recipe.range_learning, + dynamic_weights=recipe.dynamic_weights, + ) + attribute_name = name.rsplit(".", 1)[-1] + parent_of_module = get_layer_parent_by_name(model, name) + setattr(parent_of_module, attribute_name, quantized_embedding) + + logger.info(f"replaced {name} with quantized embedding") + return model + + +def replace_all_linear_with_quantized_linear( + model: nn.Module, recipe: QuantizationRecipe +) -> nn.Module: + for name, module in model.named_modules(): + if isinstance(module, nn.Linear): + if name in recipe.exclude_layers: + logger.info(f"skip layer {name} in exclude list") + else: + if recipe.weight_codebook: + weight_quantizer = CodeBookQuantizer( + n_bits=recipe.weight_bits, + features=module.out_features, + codebook_dim=recipe.codebook_dim, + ) + else: + weight_quantizer = IntQuantizer( + num_bits=recipe.weight_bits, + group_size=recipe.weight_group_size, + dynamic=recipe.dynamic_weights, + quantization_mode="symmetric", + range_learning=recipe.range_learning, + ) + quantized_linear = QuantizedLinear( + in_features=module.in_features, + out_features=module.out_features, + bias=module.bias is not None, + weight_quantizer=weight_quantizer, + weight_quantization=recipe.weight_quantization, + activation_bits=recipe.activation_bits, + activation_group_size=recipe.activation_group_size, + activation_quantization=recipe.activation_quantization, + input_quantization=recipe.input_quantization, + output_quantization=recipe.output_quantization, + dynamic_activations=recipe.dynamic_activations, + range_learning=recipe.range_learning, + ) + quantized_linear.weight = module.weight + quantized_linear.bias = module.bias + + # replace the module with the quantized linear module + attribute_name = name.rsplit(".", 1)[-1] + parent_of_module = get_layer_parent_by_name(model, name) + setattr(parent_of_module, attribute_name, quantized_linear) + + # logger.info(f"replaced {name} with quantized linear") + return model + + +def initialize_model_parameters( + model: nn.Module, recipe: QuantizationRecipe, dtype: torch.dtype = torch.float32 +) -> None: + """ + Initialize the model weights and/or codebook if codebook quantization is used + """ + if not recipe.dynamic_weights: + set_weight_min_max(model) + if recipe.weight_codebook: + kmeans_codebook(model, dtype=dtype) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/quantized_modules.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/quantized_modules.py new file mode 100644 index 0000000000000000000000000000000000000000..8cf9d5fb068b26f4eeb3c81fb93b4ba8d202ca5f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/quantized_modules.py @@ -0,0 +1,216 @@ +from typing import Optional, Tuple, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from torchao.prototype.quantization.module_swap.quantizers import ( + CodeBookQuantizer, + IntQuantizer, + __supported_group_size_strings__, +) + +SupportedQuantizers = Union[CodeBookQuantizer, IntQuantizer] + + +class WeightModuleQuantizerBase: + def set_weight_scale_to_min_max(self) -> None: + if not self.weight_quantizer.dynamic: + self.weight_quantizer.set_scale_offset_to_min_max(self.weight) + else: + raise ValueError( + "Weights are quantized dynamically, no range/scale is used" + ) + + @property + def weight_scale(self) -> torch.Tensor: + return self.weight_quantizer.scale + + @property + def quantized_weight(self) -> torch.Tensor: + return self.weight_quantizer(self.weight) + + +class QuantizedLinear(nn.Linear, WeightModuleQuantizerBase): + def __init__( + self, + activation_bits: int, + weight_quantizer: SupportedQuantizers, + input_quantization: bool = True, + output_quantization: bool = False, + activation_group_size: Union[int, str] = "per_token", + weight_quantization: bool = True, + activation_quantization: bool = True, + dynamic_activations: bool = True, + range_learning: bool = False, + scale_eps: float = 1e-9, + *args, + **kwargs, + ) -> None: + super().__init__(*args, **kwargs) + + weight_group_size, activation_group_size = self.validate_group_sizes( + weight_quantizer.group_size, activation_group_size, dynamic_activations + ) + + self.weight_quantizer: SupportedQuantizers = weight_quantizer + self.weight_quantizer.scale_eps = scale_eps + self.input_quantizer: Optional[IntQuantizer] = None + self.output_quantizer: Optional[IntQuantizer] = None + + if input_quantization: + self.input_quantizer = IntQuantizer( + num_bits=activation_bits, + group_size=activation_group_size, + dynamic=dynamic_activations, + quantization_mode="asymmetric", + range_learning=range_learning, + scale_eps=scale_eps, + ) + else: + self.input_quantizer = None + if output_quantization: + self.output_quantizer = IntQuantizer( + num_bits=activation_bits, + group_size=activation_group_size, + dynamic=dynamic_activations, + quantization_mode="asymmetric", + range_learning=range_learning, + scale_eps=scale_eps, + ) + else: + self.output_quantizer = None + + self.input_quantization = input_quantization + self.output_quantization = output_quantization + self.weight_quantization = weight_quantization + self.activation_quantization = activation_quantization + + if not weight_quantizer.dynamic: + assert isinstance(self.weight_quantizer, IntQuantizer) + self.weight_quantizer.set_scale_offset_to_min_max(self.weight) + + self.pre_transforms: nn.ModuleList = nn.ModuleList() + self.post_transforms: nn.ModuleList = nn.ModuleList() + + def forward(self, input: torch.Tensor) -> torch.Tensor: + x = input + + if self.input_quantization: + assert self.input_quantizer is not None + self.input_quantizer.quantize = self.activation_quantization + x = self.input_quantizer(x) + + for transform in self.pre_transforms: + x = transform(x) + + if self.weight_quantization: + weight = self.quantized_weight + else: + weight = self.weight + + x = F.linear(x, weight, self.bias) + + for transform in self.post_transforms: + x = transform(x) + + if self.output_quantization: + assert self.output_quantizer is not None + self.output_quantizer.quantize = self.activation_quantization + x = self.output_quantizer(x) + return x + + @staticmethod + def validate_group_sizes( + weight_group_size: Union[int, str], + activation_group_size: Union[int, str], + dynamic_activations: bool, + ) -> Tuple[Union[int, str], Union[int, str]]: + assert ( + isinstance(weight_group_size, int) + or weight_group_size in __supported_group_size_strings__ + ) + if weight_group_size == "per_token": + raise ValueError( + "per_token is only available for dynamic activation quantization" + ) + + assert ( + isinstance(activation_group_size, int) + or activation_group_size in __supported_group_size_strings__ + ) + if activation_group_size == "per_channel": + raise ValueError("per_channel is not supported for activatins") + if not dynamic_activations and activation_group_size != "per_tensor": + raise ValueError("Only per-tensor supported for static activations") + + return weight_group_size, activation_group_size + + def __repr__(self) -> str: + output_string = "QuantizedLinear(" + empty_space = " " * len(output_string) + output_string += ( + f"weight_quantizer={self.weight_quantizer} - {self.weight_quantization}, \n" + ) + if self.input_quantizer is not None: + output_string += ( + empty_space + + f"input_quant={self.input_quantizer} - {self.activation_quantization}, \n" + ) + if self.output_quantizer is not None: + output_string += ( + empty_space + + f"output_quant={self.output_quantizer} - {self.activation_quantization}, \n" + ) + if self.pre_transforms: + output_string += empty_space + f"pre_transforms={self.pre_transforms}, \n" + if self.post_transforms: + output_string += empty_space + f"post_transforms={self.post_transforms}, \n" + output_string = output_string[:-3] + output_string += ")" + return output_string + + +class QuantizedEmbedding(nn.Embedding, WeightModuleQuantizerBase): + def __init__( + self, + num_bits: int, + group_size: Union[int, str], + quantization_mode: str, + range_learning: bool = False, + scale_eps: float = 1e-9, + dynamic_weights: bool = False, + *args, + **kwargs, + ) -> None: + super().__init__(*args, **kwargs) + self.weight_quantizer = IntQuantizer( + num_bits=num_bits, + group_size=group_size, + dynamic=dynamic_weights, + quantization_mode="symmetric", + range_learning=range_learning, + scale_eps=scale_eps, + ) + self.weight_quantization = True + self.dynamic_weights = dynamic_weights + + if not self.dynamic_weights: + self.weight_quantizer.set_scale_offset_to_min_max(self.weight) + self._range_learning = range_learning + + def forward(self, input: torch.Tensor) -> torch.Tensor: + if self.weight_quantization: + weight = self.weight_quantizer(self.weight) + else: + weight = self.weight + + return torch.nn.functional.embedding( + input, + weight, + self.padding_idx, + self.max_norm, + self.norm_type, + self.scale_grad_by_freq, + self.sparse, + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/quantizers.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/quantizers.py new file mode 100644 index 0000000000000000000000000000000000000000..a6f5e7ad9530d96af393c5354200c7c00365c340 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/quantizers.py @@ -0,0 +1,347 @@ +from typing import Optional, Tuple, Union + +import torch +import torch.nn as nn +from torch.autograd import Function + +__supported_group_size_strings__ = ["per_token", "per_channel", "per_tensor"] + + +class RoundStraightThrough(Function): + @staticmethod + def forward(ctx, x: torch.Tensor) -> torch.Tensor: + return torch.round(x) + + @staticmethod + def backward(ctx, output_grad: torch.Tensor) -> torch.Tensor: + return output_grad + + +class IntQuantizer(nn.Module): + def __init__( + self, + num_bits: int, + group_size: Union[int, str], + dynamic: bool, + quantization_mode: str, + range_learning: bool = False, + scale_eps: float = 1e-9, + ) -> None: + super().__init__() + + self.num_bits = num_bits + self.group_size = group_size + self.dynamic = dynamic + self.quantization_mode = quantization_mode + self.scale_eps = scale_eps + self.scale: Optional[torch.Tensor] = None + self.offset: Optional[torch.Tensor] = None + self._range_learning = range_learning + self.quant_dtype: torch._C.dtype = torch.float32 + self.quantize = True + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if not self.quantize: + return x + + q_min, q_max = self.get_qmin_qmax( + self.num_bits, self.quant_mode_to_signed(self.quantization_mode) + ) + + if self.dynamic: + scale, offset = IntQuantizer.get_scale_offset( + x, + self.group_size, + self.quantization_mode, + q_min, + q_max, + ) + else: + scale = self.scale + offset = self.offset + + if scale is None: + raise ValueError("Initialize scale before first forward pass") + + group_size = self.process_group_size_to_int(self.group_size, x) + + if self._range_learning: + scale = torch.clamp(scale, min=self.scale_eps) + if offset is not None: + offset = RoundStraightThrough.apply(offset) + offset = torch.clamp(offset, q_min, q_max) + + return self.quantize_forward( + x, + scale=scale, + offset=offset, + group_size=group_size, + q_min=q_min, + q_max=q_max, + ) + + @property + def q_min(self) -> int: + q_min, _ = self.get_qmin_qmax( + self.num_bits, self.quant_mode_to_signed(self.quantization_mode) + ) + return q_min + + @property + def q_max(self) -> int: + _, q_max = self.get_qmin_qmax( + self.num_bits, self.quant_mode_to_signed(self.quantization_mode) + ) + return q_max + + @staticmethod + def quant_mode_to_signed(quant_mode: str) -> bool: + if quant_mode == "symmetric": + return True + elif quant_mode == "asymmetric": + return False + else: + raise NotImplementedError + + @staticmethod + def get_scale_param_size( + x: torch.Tensor, group_size: Union[int, str] + ) -> torch.Size: + int_group_size = IntQuantizer.process_group_size_to_int(group_size, x) + if int_group_size is None: + return torch.Size([1]) + else: + if len(x.shape) == 1: + return torch.Size([x.shape[0] // int_group_size]) + else: + size_list = [x.shape[i] for i in range(len(x.shape) - 1)] + size_list.append(x.shape[-1] // int_group_size) + return torch.Size(size_list) + + @staticmethod + def get_qmin_qmax(n_bits: int, signed: bool) -> Tuple[int, int]: + if signed: + qmin = -(2 ** (n_bits - 1)) + qmax = 2 ** (n_bits - 1) - 1 + else: + qmin = 0 + qmax = 2**n_bits - 1 + return qmin, qmax + + @staticmethod + def get_scale_offset( + x: torch.Tensor, + group_size: Union[int, str], + quantization_mode: str, + q_min: int, + q_max: int, + scale_eps: float = 1e-9, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]: + if not isinstance(group_size, int) and group_size == "per_tensor": + x_min = torch.min(x) + x_max = torch.max(x) + else: + int_group_size = IntQuantizer.process_group_size_to_int(group_size, x) + assert int_group_size is not None + reshaped_x = x.reshape( + [*x.shape[:-1], x.shape[-1] // int_group_size, int_group_size] + ) + x_min = torch.min(reshaped_x, dim=-1)[0] + x_max = torch.max(reshaped_x, dim=-1)[0] + + if quantization_mode == "symmetric": + scale = IntQuantizer.get_scale_from_min_max( + x_min, x_max, q_min, q_max, scale_eps + ) + offset = None + elif quantization_mode == "asymmetric": + scale, offset = IntQuantizer.get_scale_offset_from_min_max( + x_min, x_max, q_min, q_max, scale_eps + ) + else: + raise NotImplementedError + + return scale, offset + + @staticmethod + def quantize_forward( + x: torch.Tensor, + scale: torch.Tensor, + offset: Optional[torch.Tensor], + q_min: int, + q_max: int, + group_size: Optional[int] = None, + ) -> torch.Tensor: + # if quantization is per_group, we need to reshape the tensor to apply it over + reshaped = False + orig_shape = x.shape + if group_size is not None and group_size != x.shape[-1]: + x = x.reshape(*x.shape[:-1], x.shape[-1] // group_size, group_size) + scale = torch.unsqueeze(scale, -1) + if offset is not None: + offset = torch.unsqueeze(offset, -1) + reshaped = True + + if scale.device != x.device: + scale = scale.to(x.device) + if offset is not None: + offset = offset.to(x.device) + + input_dtype = x.dtype + + if offset is None or offset.numel() == 0: + x = torch.clamp(RoundStraightThrough.apply(x / scale), q_min, q_max) + x = x * scale + else: + x = torch.clamp( + RoundStraightThrough.apply(x / scale) + offset, + q_min, + q_max, + ) + x = (x - offset) * scale + + # reshape back to original shape if groups were used + if reshaped: + x = x.reshape(orig_shape) + + return x.to(input_dtype) + + @staticmethod + def process_group_size_to_int( + group_size: Union[int, str], x: torch.Tensor + ) -> Optional[int]: + if isinstance(group_size, int): + return group_size + elif group_size == "per_channel" or group_size == "per_token": + return x.shape[-1] + elif group_size == "per_tensor": + return None + else: + raise NotImplementedError + + @staticmethod + def get_scale_from_min_max( + x_min: torch.Tensor, + x_max: torch.Tensor, + q_min: int, + q_max: int, + eps: float = 1e-9, + ) -> torch.Tensor: + smin = x_min / float(q_min) + smax = x_max / float(q_max) + mask = smin > smax + scale = torch.where(mask, smin, smax) + scale = torch.clamp(scale, min=eps) + return scale + + @staticmethod + def get_scale_offset_from_min_max( + x_min: torch.Tensor, + x_max: torch.Tensor, + q_min: int, + q_max: int, + eps: float = 1e-9, + ) -> Tuple[torch.Tensor, torch.Tensor]: + scale = ((x_max - x_min) / (abs(q_min) + abs(q_max))).detach() + offset = (-x_min / scale).detach() + + offset = torch.round(offset) + offset = torch.clamp(offset, q_min, q_max) + + scale = torch.clamp(scale, min=eps) + return scale, offset + + def set_scale_offset_to_min_max(self, x: torch.Tensor) -> None: + assert not self.dynamic + + x = x.detach() + x = x.to(self.quant_dtype) + + signed = self.quant_mode_to_signed(self.quantization_mode) + + q_min, q_max = self.get_qmin_qmax(self.num_bits, signed=signed) + scale, offset = self.get_scale_offset( + x, self.group_size, self.quantization_mode, q_min, q_max + ) + + # with per-tensor we get empty tensors sometimes + if scale.data.shape == torch.Size([]): + scale_size_fix = torch.ones([1]).to(scale.device) + scale_size_fix *= scale + scale.data = scale_size_fix.data + + if self._range_learning: + self.scale = torch.nn.Parameter(scale, requires_grad=True).to( + self.quant_dtype + ) + if offset is not None: + self.offset = torch.nn.Parameter(offset, requires_grad=True).to( + self.quant_dtype + ) + else: + self.scale = scale + self.offset = offset + + +class CodeBookQuantizer(nn.Module): + def __init__( + self, + n_bits: int, + features: int, + codebook_dim: int = 1, + seed: int = 1337, + ) -> None: + super().__init__() + self.group_size = codebook_dim + self.codebook_dim = codebook_dim + self.dynamic = True + self.scale_eps = 1e-9 + assert features % codebook_dim == 0 + torch.manual_seed(seed) + + N = 2 ** (n_bits * codebook_dim) + codebook_shape = (N, codebook_dim) + self.codebook = nn.Parameter( + torch.Tensor(codebook_shape[0], codebook_shape[1]), requires_grad=False + ) + + self._codebook_shape: Tuple[int, int] = codebook_shape + + def forward(self, x: torch.Tensor) -> torch.Tensor: + scaling_factor = torch.mean(abs(x), dim=1, keepdim=True).detach() + output = scaling_factor * VectorQuantizerFunction.apply( + x / scaling_factor, self.codebook + ) + return output + + +class VectorQuantizerFunction(torch.autograd.Function): + @staticmethod + # pyre-ignore[2, 14] + def forward(ctx, inputs: torch.Tensor, codebook: torch.Tensor) -> torch.Tensor: + flat_inputs = inputs.view(-1, codebook.shape[1]) + distances = torch.cdist(flat_inputs, codebook) + indices = torch.argmin(distances, dim=1) + sums = torch.zeros_like(codebook).float().cuda() + counts = torch.zeros(codebook.size(0), dtype=torch.float).cuda() + + # Accumulate sums using index_add_ + sums.index_add_(0, indices, flat_inputs.float()) + + # Accumulate counts using index_add_ + ones = torch.ones(flat_inputs.size(0), dtype=torch.float).cuda() + counts.index_add_(0, indices, ones) + + # Avoid division by zero + counts = counts.unsqueeze(1).clamp(min=1.0) + + # Update each centroid with the average of assigned inputs + codebook.copy_(sums / counts) + + quantized = codebook[indices].view_as(inputs) + return quantized + + @staticmethod + # pyre-ignore[2, 14] + def backward(ctx, grad_output: torch.Tensor) -> Tuple[torch.Tensor, None]: + return grad_output, None diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/range_setting_methods.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/range_setting_methods.py new file mode 100644 index 0000000000000000000000000000000000000000..2ba93321fbe25236e3227436ad235e79c1744715 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/range_setting_methods.py @@ -0,0 +1,216 @@ +import copy +import logging +from typing import Callable, Optional + +import torch +import torch.nn as nn + +from torchao.prototype.quantization.module_swap.data_getters import ( + DataGetter, + get_module_input_data, +) +from torchao.prototype.quantization.module_swap.quantized_modules import ( + QuantizedLinear, +) +from torchao.prototype.quantization.module_swap.utils import ( + all_activation_quantizers_off, + all_quantizers_off, + all_weight_quantizers_on, +) + +logger: logging.Logger = logging.getLogger(__name__) + + +def set_weight_min_max(model: nn.Module) -> None: + for _, module in model.named_modules(): + if isinstance(module, QuantizedLinear): + module.set_weight_scale_to_min_max() + + +def set_weight_mse( + model: nn.Module, num_points: int = 100, max_shrink: float = 0, norm: float = 2.0 +) -> None: + for _, module in model.named_modules(): + if isinstance(module, QuantizedLinear): + loss_fn = lambda m: torch.sum( # noqa + torch.pow(torch.abs(m.weight - m.quantized_weight), norm), dim=-1 + ) + best_scale = find_optimal_scales_with_loss( + module, loss_fn, num_points, max_shrink + ) + module.weight_scale.data = best_scale + + +def get_batched_output( + module: nn.Module, input_data: torch.Tensor, batch_size: int +) -> torch.Tensor: + device = module.weight.device + dtype = module.weight.dtype + + num_samples = input_data.shape[0] + num_batches = num_samples // batch_size + + output_data = [] + for i in range(num_batches): + this_batch = input_data[i * batch_size : (i + 1) * batch_size] + this_batch = this_batch.to(device).to(dtype) + output_data.append(module(this_batch).to(torch.float32).to("cpu")) + + return torch.vstack(output_data) + + +def set_weight_range_activation_loss( + model: nn.Module, + data: torch.Tensor, + batch_size: int, + num_points: int = 100, + progressive: bool = True, + data_getter: Optional[DataGetter] = None, +) -> None: + # store quantization settings so this algorithm does not change those implicitly + quantization_setting_mapping_dict = { + name: [module.weight_quantization, module.activation_quantization] + for name, module in model.named_modules() + if isinstance(module, QuantizedLinear) + } + + data_getter_progressive = None + if data_getter is not None: + data_getter.initialize(model, data, batch_size) + if progressive: + data_getter_progressive = copy.deepcopy(data_getter) + + # TODO: This can all be optimized for efficiency (keep data on GPU) or Memory (keep data on CPU) + # Do the actual range setting + with torch.no_grad(): + for name, module in model.named_modules(): + if isinstance(module, QuantizedLinear): + logger.info(f"Range setting for {name}") + model.apply(all_quantizers_off) + # TODO: Some form of smart subsampling from all this sequential data + if data_getter is not None: + input_data = data_getter.pop(model, name) + else: + input_data = get_module_input_data(model, data, module, batch_size) + output_data = get_batched_output(module, input_data, batch_size) + + if progressive: + model.apply(all_weight_quantizers_on) + if data_getter_progressive is not None: + input_data = data_getter_progressive.pop(model, name) + else: + input_data = get_module_input_data( + model, data, module, batch_size + ) + + input_data = input_data.to(module.weight.device).to(module.weight.dtype) + output_data = output_data.to(module.weight.device).to( + module.weight.dtype + ) + + module.weight_quantization = True + dim = tuple(range(input_data.dim() - 1)) # all but last + + # TODO: batched loss getting + loss_fn = lambda m: torch.mean( # noqa + torch.pow(m(input_data) - output_data, 2), + dim=dim, # noqa + ) + + best_scale = find_optimal_scales_with_loss(module, loss_fn, num_points) + module.weight_scale.data = best_scale + + # reset quantization settings to original values + for name, module in model.named_modules(): + if isinstance(module, QuantizedLinear): + module.weight_quantization, module.activation_quantization = ( + quantization_setting_mapping_dict[name] + ) + + +def set_activation_min_max( + model: nn.Module, data: torch.Tensor, batch_size: int +) -> None: + # store quantization settings so this algorithm does not change those implicitly + quantization_setting_mapping_dict = { + name: [module.weight_quantization, module.activation_quantization] + for name, module in model.named_modules() + if isinstance(module, QuantizedLinear) + } + + model.apply(all_activation_quantizers_off) + for name, module in model.named_modules(): + if isinstance(module, QuantizedLinear): + logger.info(f"Activation min/max setting for {name}") + input_data = None + if module.input_quantization: + input_data = get_module_input_data(model, data, module, batch_size) + assert module.input_quantizer is not None + module.input_quantizer.set_scale_offset_to_min_max(input_data) + if module.output_quantization: + if input_data is None: + input_data = get_module_input_data(model, data, module, batch_size) + output_data = module(input_data) + assert module.output_quantizer is not None + module.output_quantizer.set_scale_offset_to_min_max(output_data) + + # reset quantization settings to original values + for name, module in model.named_modules(): + if isinstance(module, QuantizedLinear): + module.weight_quantization, module.activation_quantization = ( + quantization_setting_mapping_dict[name] + ) + + +def find_optimal_scales_with_loss( + module: QuantizedLinear, + loss_fn: Callable[[nn.Module], torch.Tensor], + num_points: int, + max_shrink: float = 0, +) -> torch.Tensor: + assert max_shrink >= 0 and max_shrink < 1.0 + assert num_points > 0 + + with torch.no_grad(): + grid = torch.linspace(max_shrink, 1, num_points + 1) + module.set_weight_scale_to_min_max() + + orig_scales = module.weight_scale.clone() + best_scale = module.weight_scale.clone() + best_loss = loss_fn(module) + + for i in range(0, num_points - 1): + test_scale = orig_scales * grid[i] + module.weight_scale.data = test_scale + loss = loss_fn(module) + mask = loss < best_loss + best_loss[mask] = loss[mask] + best_scale[mask] = test_scale[mask] + return best_scale + + +def quantize_per_group_scales(model: nn.Module, bit_width: int) -> None: + for name, module in model.named_modules(): + if isinstance(module, QuantizedLinear): + scale = module.weight_quantizer.scale + assert isinstance(scale, torch.Tensor) + + if len(scale.shape) < 2 or scale.shape[-1] == 1: + logger.warning( + f"Module {name} is not quantized with group_wise quantization" + ) + continue + + per_channel_scales = torch.max(scale, dim=-1, keepdim=True).values + scale = scale / per_channel_scales # scale to [0, 1] + + # quantize the per_group scale to bit_width + quant_max = 2.0**bit_width + scale = ( + torch.clamp(torch.ceil(scale * quant_max), min=1.0, max=quant_max) + / quant_max + ) # ceil to make sure clipping error is certainly 0 + + scale = scale * per_channel_scales # fuse the fp16 scale + + module.weight_quantizer.scale.data = scale diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b39dd9479ae35a4af073fddecd37d2e6180bcb90 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/module_swap/utils.py @@ -0,0 +1,71 @@ +from typing import Dict + +import torch.nn as nn + +from torchao.prototype.quantization.module_swap.quantized_modules import QuantizedLinear +from torchao.prototype.quantization.module_swap.quantizers import IntQuantizer + + +def get_layer_by_name(model: nn.Module, query_name: str) -> nn.Module: + """ + Retrieves a layer from a PyTorch model by its name. + + Args: + model (nn.Module): The PyTorch model. + name (str): The name of the layer to retrieve. + + Returns: + nn.Module: The retrieved layer. + """ + for name, module in model.named_modules(): + if name == query_name: + return module + raise ValueError(f"Layer '{query_name}' not found in model") + + +def all_quantizers_off(module: nn.Module) -> None: + if isinstance(module, QuantizedLinear): + module.weight_quantization = False + module.activation_quantization = False + + +def all_quantizers_on(module: nn.Module) -> None: + if isinstance(module, QuantizedLinear): + module.weight_quantization = True + module.activation_quantization = True + + +def all_activation_quantizers_off(module: nn.Module) -> None: + if isinstance(module, QuantizedLinear): + module.activation_quantization = False + + +def all_activation_quantizers_on(module: nn.Module) -> None: + if isinstance(module, QuantizedLinear): + module.activation_quantization = True + + +def all_weight_quantizers_on(module: nn.Module) -> None: + if isinstance(module, QuantizedLinear): + module.weight_quantization = True + + +def set_bit_widths_by_name( + model: nn.Module, bit_width_dict: Dict[str, Dict[str, int]] +) -> None: + for name, bit_width_assignment in bit_width_dict.items(): + this_layer = get_layer_by_name(model, name) + for quantizer, bit_width in bit_width_assignment.items(): + assert isinstance(this_layer, QuantizedLinear) + if quantizer == "weight": + assert isinstance(this_layer.weight_quantizer, IntQuantizer) + this_layer.weight_quantizer.num_bits = bit_width + elif quantizer == "activation": + if this_layer.input_quantizer is not None: + this_layer.input_quantizer.num_bits = bit_width + if this_layer.output_quantizer is not None: + this_layer.output_quantizer.num_bits = bit_width + else: + raise ValueError( + f"Unknown quantizer {quantizer}, should be either 'weight' or 'activation'" + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/uintx/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/uintx/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/uintx/uintx_bit_packed_tensor.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/uintx/uintx_bit_packed_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..920dc3c06a45995213e2ded8c1952b3dda179196 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/quantization/uintx/uintx_bit_packed_tensor.py @@ -0,0 +1,401 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +import copy +from typing import Dict, Optional + +import torch +from torch.utils._python_dispatch import return_and_correct_aliasing + +from torchao.utils import TorchAOBaseTensor, fill_defaults + +try: + import gemlite +except (ImportError, ModuleNotFoundError): + gemlite = None + +aten = torch.ops.aten + + +class UIntxBitPackedTensor(TorchAOBaseTensor): + """Packed unsigned integer weight tensor using gemlite (https://github.com/dropbox/gemlite) bit-packing. + see Tensor attributes for more details. + + Supports 4-bit (asymmetric, grouped) and 8-bit (symmetric, per-channel) weight-only + quantization. Supported bit widths: 4, 8. Supported packing bit widths: 8, 16, 32 + (or None to let gemlite choose automatically). + + Tensor Attributes: + qdata: Quantized weight data, stored in transposed layout + (in_features-major). For 4-bit: multiple values are bit-packed LSB-first + along the in_features axis into a packing container (int8 for + packing_bitwidth=8, int16 for 16, int32 for 32). Shape is + (in_features // elements_per_sample, out_features) where + elements_per_sample = packing_bitwidth // bit_width. For 8-bit: stored + unpacked as int8 with shape (in_features, out_features). + See gemlite.bitpack for the full packing implementation. + scale: quantization scale factors + zero_point: quantization zero points (empty tensor for symmetric) + + Non-Tensor Attributes: + gemlite_kwargs: dict with gemlite metadata (in_features, out_features, meta_args, etc.) + bit_width: quantization bit width (4 or 8) + group_size: quantization group size (32, 64, 128, 256, 512, 1024, or None for per-channel) + dtype: original weight dtype + """ + + tensor_data_names = ["qdata", "scale", "zero_point"] + tensor_attribute_names = [ + "gemlite_kwargs", + "bit_width", + "group_size", + "dtype", + ] + + def __new__( + cls, + qdata: torch.Tensor, + scale: torch.Tensor, + zero_point: torch.Tensor, + gemlite_kwargs: Dict, + bit_width: int, + group_size: int, + dtype: torch.dtype, + ): + shape = (gemlite_kwargs["out_features"], gemlite_kwargs["in_features"]) + return torch.Tensor._make_wrapper_subclass( + cls, + shape, + device=qdata.device, + dtype=dtype, + requires_grad=False, + ) + + def __init__( + self, + qdata: torch.Tensor, + scale: torch.Tensor, + zero_point: torch.Tensor, + gemlite_kwargs: Dict, + bit_width: int, + group_size: int, + dtype: torch.dtype, + ): + self.qdata = qdata + self.scale = scale + self.zero_point = zero_point + self.gemlite_kwargs = gemlite_kwargs + self.bit_width = bit_width + self.group_size = group_size + # Note: don't set self.dtype, it's handled by __new__ via _make_wrapper_subclass + + @classmethod + def from_hp( + cls, + hp_tensor: torch.Tensor, + bit_width: int = 4, + group_size: Optional[int] = 128, + packing_bitwidth: Optional[int] = None, + mode: str = "weight_only", + ): + """Create UIntxBitPackedTensor from a high-precision weight tensor. + + Args: + hp_tensor: the float weight tensor (out_features, in_features) + bit_width: 4 or 8 + group_size: quantization group size, None means per-channel + packing_bitwidth: 8, 16, 32, or None (let gemlite choose) + mode: "weight_only" or "dynamic" + """ + if gemlite is None: + raise ImportError("gemlite is required. Install with: pip install gemlite") + + assert hp_tensor.dtype in [torch.float16, torch.bfloat16], ( + f"dtype must be float16 or bfloat16, got {hp_tensor.dtype}" + ) + assert mode in ["weight_only", "dynamic"] + + out_features, in_features = hp_tensor.shape + effective_group_size = in_features if group_size is None else group_size + device = hp_tensor.device + + # Step 1: Quantize the weight + int_data, scale, zero_point = cls._quantize_weight( + hp_tensor, bit_width, effective_group_size + ) + + # Step 2: Pack with gemlite + if int_data.device.type != "cuda": + int_data = int_data.cuda() + + if bit_width == 8 and effective_group_size == in_features: + processor = ( + gemlite.helper.A8W8_int8_dynamic + if mode == "dynamic" + else gemlite.helper.A16W8 + ) + gemlite_linear = processor(device=int_data.device).from_weights( + int_data, scales=scale, bias=None + ) + else: + if mode == "dynamic": + if hasattr(gemlite.helper, "A8Wn_dynamic"): + gemlite_linear = gemlite.helper.A8Wn_dynamic( + device=int_data.device, packing_bitwidth=packing_bitwidth + ).from_weights( + int_data, + scale, + zero_point, + bit_width, + effective_group_size, + bias=None, + ) + elif hasattr(gemlite.helper, "A8Wn_HQQ_INT_dynamic"): + gemlite_linear = gemlite.helper.A8Wn_HQQ_INT_dynamic( + device=int_data.device, + packing_bitwidth=packing_bitwidth, + W_nbits=bit_width, + ).from_weights(int_data, scale, zero_point, bias=None) + else: + raise ImportError( + "gemlite does not have A8Wn_dynamic or A8Wn_HQQ_INT_dynamic" + ) + else: + gemlite_linear = gemlite.helper.A16Wn( + device=int_data.device, packing_bitwidth=packing_bitwidth + ).from_weights( + int_data, + scale, + zero_point, + bit_width, + effective_group_size, + bias=None, + ) + + meta_args = gemlite_linear.get_meta_args() + gemlite_kwargs = { + "in_features": in_features, + "out_features": out_features, + "packing_bitwidth": packing_bitwidth, + "data_contiguous": gemlite_linear.data_contiguous, + "elements_per_sample": gemlite_linear.elements_per_sample, + "W_group_mode": gemlite_linear.W_group_mode, + "meta_args": meta_args, + } + + qdata, scale, zero_point = gemlite_linear.get_tensor_args() + qdata = qdata.to(device) + if zero_point is None: + zero_point = torch.tensor([[]], device=qdata.device, dtype=torch.int32) + + return cls( + qdata, + scale, + zero_point, + gemlite_kwargs, + bit_width, + effective_group_size, + hp_tensor.dtype, + ) + + @classmethod + def _quantize_weight(cls, hp_tensor, bit_width, group_size): + """Quantize weight tensor to int data + scale + zero_point.""" + from torchao.quantization.quant_primitives import ( + MappingType, + choose_qparams_affine, + quantize_affine, + ) + + block_size = (1, group_size) + + if bit_width == 4: + # Use HQQ for 4-bit (better quality) + from torchao.quantization.quant_primitives import ( + _choose_qparams_and_quantize_affine_hqq, + ) + + int_data, scale, zero_point, _ = _choose_qparams_and_quantize_affine_hqq( + hp_tensor, + nbits=bit_width, + group_size=group_size, + raw_output=True, + ) + return int_data, scale, zero_point + + else: + # 8-bit: symmetric + scale, zero_point = choose_qparams_affine( + hp_tensor, + mapping_type=MappingType.SYMMETRIC, + block_size=block_size, + target_dtype=torch.int8, + quant_min=-128, + quant_max=127, + eps=1e-5, + ) + int_data = quantize_affine( + hp_tensor, + block_size=block_size, + scale=scale, + zero_point=zero_point, + output_dtype=torch.int8, + quant_min=-128, + quant_max=127, + ) + return int_data, scale, zero_point + + def dequantize(self, output_dtype=None): + """Dequantize packed weight back to floating point.""" + device = self.qdata.device + if self.bit_width == 8: + # 8-bit weights are stored unpacked as int8 (transposed to K x N). + # Skip unpack_over_rows which would incorrectly reinterpret signed + # int8 bit patterns as unsigned uint8. + int_data = self.qdata.t() + else: + int_data = ( + gemlite.bitpack.unpack_over_rows( + self.qdata.cuda(), + W_nbits=self.bit_width, + num_output_rows=self.gemlite_kwargs["in_features"], + dtype=torch.uint8, + ) + .to(device) + .t() + ) + + if self.gemlite_kwargs["data_contiguous"]: + int_data = int_data.contiguous() + + # Handle FMA mode: W_q * s + z -> (W_q - z) * s + if self.gemlite_kwargs["W_group_mode"] == 4: + scale_min_val = 1e-8 + scale = self.scale.clone().float() + scale[torch.logical_and(scale >= 0, scale.abs() <= scale_min_val)] = ( + scale_min_val + ) + scale[ + torch.logical_and(scale < 0, scale.abs() <= scale_min_val) + ] = -scale_min_val + zero_point = (-self.zero_point.float() / scale).clamp_(-100, 100) + zero_point = zero_point.to(self.scale.dtype) + else: + zero_point = self.zero_point + + scale = self.scale.t().contiguous() + # For symmetric quantization (8-bit), zero_point is stored as an empty + # tensor. Replace with zeros matching scale shape for dequantize_affine. + if zero_point.numel() == 0: + zero_point = torch.zeros_like(scale) + else: + zero_point = zero_point.t().contiguous() + + # Dequantize: (int_data - zero_point) * scale + from torchao.quantization.quant_primitives import dequantize_affine + + block_size = (1, self.group_size) + result = dequantize_affine( + int_data, + block_size=block_size, + scale=scale, + zero_point=zero_point, + input_dtype=int_data.dtype, + output_dtype=output_dtype or self.dtype, + ) + return result + + +# Allow weights_only=True in torch.load +torch.serialization.add_safe_globals([UIntxBitPackedTensor]) + +# Register aten op implementations +implements = UIntxBitPackedTensor.implements +implements_torch_function = UIntxBitPackedTensor.implements_torch_function + + +@implements(aten.linear.default) +@implements_torch_function(torch.nn.functional.linear) +def _(func, types, args, kwargs): + input_tensor, weight_tensor = args[0], args[1] + bias = args[2] if len(args) > 2 else None + + assert isinstance(weight_tensor, UIntxBitPackedTensor) + + return gemlite.core.forward_functional( + x=input_tensor, + bias=bias, + tensor_args=( + weight_tensor.qdata, + weight_tensor.scale, + weight_tensor.zero_point, + ), + meta_args=weight_tensor.gemlite_kwargs["meta_args"], + ) + + +@implements(aten.t.default) +def _(func, types, args, kwargs): + # No-op: gemlite expects non-transposed weight, and F.linear decomposes to t + mm + return return_and_correct_aliasing( + func, args, kwargs or {}, args[0]._apply_fn_to_data(torch.detach) + ) + + +@implements(aten.slice.Tensor) +def _(func, types, args, kwargs): + self, dim, start, end, step = fill_defaults(args, 5, [0, None, None, 1]) + assert step == 1, "Only step == 1 is supported" + + if dim not in [0, 1]: + raise NotImplementedError( + f"UIntxBitPackedTensor: slice on dim={dim} not supported" + ) + + # Data is stored transposed (K x N), so flip the dim + data_dim = 1 - dim + qdata = self.qdata + scale = self.scale + zero_point = self.zero_point + + # meta_args is shape-independent (contains only quantization config like bit_width, + # group_size, dtype enums, etc.) so it doesn't need updating after slicing. + # forward_functional derives matrix dimensions from the qdata tensor shape. + gemlite_kwargs = copy.deepcopy(self.gemlite_kwargs) + orig_shape = [ + gemlite_kwargs["in_features"], + gemlite_kwargs["out_features"], + ] + elements_per_sample = gemlite_kwargs["elements_per_sample"] + data_len = orig_shape[data_dim] + scale_len = scale.shape[data_dim] + ratio = data_len / scale_len + start_scale = int(start / ratio) + end_scale = int(end / ratio) + + # For packing only the K dimension + div = elements_per_sample if data_dim == 0 else 1 + qdata = aten.slice.Tensor(qdata, data_dim, start // div, end // div, step) + + gemlite_kwargs["in_features"] = qdata.shape[0] * elements_per_sample + gemlite_kwargs["out_features"] = qdata.shape[1] + + scale = aten.slice.Tensor(scale, data_dim, start_scale, end_scale, step) + if zero_point is not None and zero_point.numel() > 0: + zero_point = aten.slice.Tensor( + zero_point, data_dim, start_scale, end_scale, step + ) + + sliced = UIntxBitPackedTensor( + qdata, + scale, + zero_point, + gemlite_kwargs, + self.bit_width, + self.group_size, + self.dtype, + ) + return return_and_correct_aliasing(func, args, kwargs or {}, sliced) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/tensor_conversion/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/tensor_conversion/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2b3f290968aa632e0454313ec2b5a6b70943695 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/tensor_conversion/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/tensor_conversion/__pycache__/api.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/tensor_conversion/__pycache__/api.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad315de00d0ddaca2ac31c46aac81b8c109cfb56 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/tensor_conversion/__pycache__/api.cpython-310.pyc differ