LT99's picture
release(v1.0.0): initial 3.3 BPW 3-shard Lazy Towers multimodal release (294.27 MiB, E2E certified)
8c16eba
Raw History Blame Contribute Delete
11.2 kB
"""Packed mixed-precision (2-bit / 3-bit QuaRot H64 Lloyd-Max / 4-bit Asym + AWQ) inference layers."""
import math
import torch
from torch import nn
from torch.nn import functional as F
# Symmetric 1-D Gaussian N(0, 1) Lloyd-Max optimal centroids (3-bit).
LLOYD_3BIT = (-2.1519465, -1.3439093, -0.7560053, -0.2450942, 0.2450942, 0.7560053, 1.3439093, 2.1519465)
_H64_CACHE = {}
def hadamard_matrix(n: int = 64, device=None, dtype=torch.float32) -> torch.Tensor:
h = torch.tensor([[1.0]], dtype=torch.float32, device=device)
while h.shape[0] < n:
h = torch.cat([torch.cat([h, h], dim=1), torch.cat([h, -h], dim=1)], dim=0)
return (h / math.sqrt(float(n))).to(dtype)
def get_h64(device, dtype=torch.float32) -> torch.Tensor:
key = (str(device), dtype)
if key not in _H64_CACHE:
_H64_CACHE[key] = hadamard_matrix(64, device=device, dtype=dtype)
return _H64_CACHE[key]
def _bytes_per_block(bits: int, block_size: int) -> int:
if bits == 2:
return block_size // 4
if bits == 3:
return (block_size // 8) * 3
if bits == 4:
return block_size // 2
raise ValueError(f"Unsupported bit width: {bits}")
def unpack_nbit(packed: torch.Tensor, bits: int, block_size: int) -> torch.Tensor:
"""Unpacks uint8 block bytes back into integer codes (..., block_size)."""
if bits == 2:
p = packed.to(torch.int32)
out = torch.stack([p & 3, (p >> 2) & 3, (p >> 4) & 3, (p >> 6) & 3], dim=-1)
return out.reshape(*packed.shape[:-1], block_size).long()
if bits == 4:
p = packed.to(torch.int32)
out = torch.stack([p & 15, (p >> 4) & 15], dim=-1)
return out.reshape(*packed.shape[:-1], block_size).long()
if bits == 3:
b3 = packed.reshape(*packed.shape[:-1], block_size // 8, 3).to(torch.int32)
p24 = b3[..., 0] | (b3[..., 1] << 8) | (b3[..., 2] << 16)
out = torch.stack([(p24 >> (3 * k)) & 7 for k in range(8)], dim=-1)
return out.reshape(*packed.shape[:-1], block_size).long()
raise ValueError(f"Unsupported unpack bit width: {bits}")
def dequantize_blocks(
packed: torch.Tensor,
scale: torch.Tensor,
bits: int,
mode: str,
block_size: int = 64,
w_min: torch.Tensor = None,
awq_inv_scale: torch.Tensor = None,
cols: int = None,
dtype=torch.float32,
) -> torch.Tensor:
codes = unpack_nbit(packed, bits, block_size)
if mode == "hada_lloyd":
levels = torch.tensor(LLOYD_3BIT, device=packed.device, dtype=torch.float32)
q_rot = levels[codes] * scale.float().unsqueeze(-1)
h64 = get_h64(packed.device, torch.float32)
w = (q_rot @ h64.T).reshape(*packed.shape[:-2], -1)
elif mode == "asym_uint":
w = (codes.float() * scale.float().unsqueeze(-1) + w_min.float().unsqueeze(-1)).reshape(*packed.shape[:-2], -1)
else:
raise ValueError(f"Unknown quantization mode: {mode}")
if cols is not None and w.shape[-1] != cols:
w = w[..., :cols]
if awq_inv_scale is not None:
w = w * awq_inv_scale.float()
return w.to(dtype)
class PackedQuantLinear(nn.Module):
"""Packed 3-bit QuaRot H64 Lloyd-Max or 4-bit Asymmetric + AWQ Linear layer."""
def __init__(self, out_features: int, in_features: int, bits: int, mode: str, block_size: int = 64, has_bias: bool = False, has_awq: bool = False, tensors: dict = None):
super().__init__()
self.out_features = out_features
self.in_features = in_features
self.bits = bits
self.mode = mode
self.block_size = block_size
n_blocks = math.ceil(in_features / block_size)
bpb = _bytes_per_block(bits, block_size)
self.register_buffer("packed", tensors["packed"] if tensors is not None else torch.empty((out_features, n_blocks, bpb), dtype=torch.uint8))
self.register_buffer("scale", tensors["scale"] if tensors is not None else torch.empty((out_features, n_blocks), dtype=torch.float16))
if mode == "asym_uint":
self.register_buffer("w_min", tensors["w_min"] if tensors is not None else torch.empty((out_features, n_blocks), dtype=torch.float16))
else:
self.w_min = None
if has_awq:
self.register_buffer("awq_inv_scale", tensors["awq_inv_scale"] if tensors is not None else torch.empty((in_features,), dtype=torch.float16))
else:
self.awq_inv_scale = None
if has_bias:
self.bias = nn.Parameter(tensors["bias"].float() if tensors is not None else torch.empty((out_features,), dtype=torch.float32), requires_grad=False)
else:
self.register_parameter("bias", None)
def forward(self, x: torch.Tensor) -> torch.Tensor:
w = dequantize_blocks(
self.packed, self.scale, self.bits, self.mode,
block_size=self.block_size, w_min=self.w_min, awq_inv_scale=self.awq_inv_scale,
cols=self.in_features, dtype=x.dtype,
)
bias = self.bias.to(x.dtype) if self.bias is not None else None
return F.linear(x, w, bias)
class PackedQuantEmbedding(nn.Module):
"""Row-gathered packed embedding table (never unpacks full vocabulary)."""
def __init__(self, num_embeddings: int, embedding_dim: int, bits: int, mode: str, block_size: int = 128, scale: float = 1.0, padding_idx=None, tensors: dict = None):
super().__init__()
self.num_embeddings = num_embeddings
self.embedding_dim = embedding_dim
self.bits = bits
self.mode = mode
self.block_size = block_size
self.scale = float(scale)
self.padding_idx = padding_idx
n_blocks = math.ceil(embedding_dim / block_size)
bpb = _bytes_per_block(bits, block_size)
self.register_buffer("packed", tensors["packed"] if tensors is not None else torch.empty((num_embeddings, n_blocks, bpb), dtype=torch.uint8))
self.register_buffer("blk_scale", tensors["blk_scale"] if tensors is not None else torch.empty((num_embeddings, n_blocks), dtype=torch.float16))
if mode == "asym_uint":
self.register_buffer("w_min", tensors["w_min"] if tensors is not None else torch.empty((num_embeddings, n_blocks), dtype=torch.float16))
else:
self.w_min = None
def forward(self, ids: torch.Tensor) -> torch.Tensor:
orig_shape = ids.shape
flat_ids = ids.reshape(-1)
p_sel = self.packed[flat_ids]
s_sel = self.blk_scale[flat_ids]
wm_sel = self.w_min[flat_ids] if self.w_min is not None else None
out = dequantize_blocks(p_sel, s_sel, self.bits, self.mode, block_size=self.block_size, w_min=wm_sel, cols=self.embedding_dim)
return (out * self.scale).reshape(*orig_shape, self.embedding_dim)
class PackedQuantPatchEmbedder(nn.Module):
"""4-bit block-64 packed vision patch position embedding table plus packed input_proj."""
def __init__(self, original, bits: int, mode: str, block_size: int = 64, tensors: dict = None):
super().__init__()
self.input_proj = original.input_proj
self.position_embedding_size = original.position_embedding_size
self.hidden_size = original.hidden_size
self.bits = bits
self.mode = mode
self.block_size = block_size
n_rows = 2 * self.position_embedding_size
n_blocks = math.ceil(self.hidden_size / block_size)
bpb = _bytes_per_block(bits, block_size)
self.register_buffer("pos_packed", tensors["pos_packed"] if tensors is not None else torch.empty((n_rows, n_blocks, bpb), dtype=torch.uint8))
self.register_buffer("pos_scale", tensors["pos_scale"] if tensors is not None else torch.empty((n_rows, n_blocks), dtype=torch.float16))
if mode == "asym_uint":
self.register_buffer("pos_w_min", tensors["pos_w_min"] if tensors is not None else torch.empty((n_rows, n_blocks), dtype=torch.float16))
else:
self.pos_w_min = None
def _gather_rows(self, indices: torch.Tensor) -> torch.Tensor:
orig_shape = indices.shape
flat = indices.reshape(-1)
p = self.pos_packed[flat]
s = self.pos_scale[flat]
wm = self.pos_w_min[flat] if self.pos_w_min is not None else None
out = dequantize_blocks(p, s, self.bits, self.mode, block_size=self.block_size, w_min=wm, cols=self.hidden_size)
return out.reshape(*orig_shape, self.hidden_size)
def forward(self, pixel_values: torch.Tensor, pixel_position_ids: torch.Tensor, padding_positions: torch.Tensor) -> torch.Tensor:
positions = pixel_position_ids.clamp_min(0)
pos_x = self._gather_rows(positions[..., 0])
pos_y = self._gather_rows(positions[..., 1] + self.position_embedding_size)
pos = torch.where(padding_positions.unsqueeze(-1), 0.0, pos_x + pos_y)
return self.input_proj(2 * (pixel_values.float() - 0.5)) + pos
def install_shard_modules(model: nn.Module, modules_spec: dict, tensor_map: dict):
"""Installs packed modules for a single shard bottom-up (so patch_embedder wraps packed input_proj)."""
order = {"linear": 0, "embedding": 1, "patch_embedder": 2}
items = sorted(modules_spec.items(), key=lambda kv: order.get(kv[1]["kind"], 9))
for name, spec in items:
original = model.get_submodule(name)
m, n = spec["shape"]
kind = spec["kind"]
bits = spec["bits"]
mode = spec["mode"]
bs = spec.get("block_size", 64)
if kind == "linear":
has_bias = spec.get("has_bias", False)
has_awq = spec.get("has_awq", False)
tensors = {
"packed": tensor_map.pop(f"{name}.packed"),
"scale": tensor_map.pop(f"{name}.scale"),
}
if mode == "asym_uint":
tensors["w_min"] = tensor_map.pop(f"{name}.w_min")
if has_awq:
tensors["awq_inv_scale"] = tensor_map.pop(f"{name}.awq_inv_scale")
if has_bias:
tensors["bias"] = tensor_map.pop(f"{name}.bias")
replacement = PackedQuantLinear(m, n, bits, mode, block_size=bs, has_bias=has_bias, has_awq=has_awq, tensors=tensors)
elif kind == "embedding":
tensors = {
"packed": tensor_map.pop(f"{name}.packed"),
"blk_scale": tensor_map.pop(f"{name}.blk_scale"),
}
if mode == "asym_uint":
tensors["w_min"] = tensor_map.pop(f"{name}.w_min")
replacement = PackedQuantEmbedding(m, n, bits, mode, block_size=bs, scale=spec["scale"], padding_idx=original.padding_idx, tensors=tensors)
elif kind == "patch_embedder":
tensors = {
"pos_packed": tensor_map.pop(f"{name}.pos_packed"),
"pos_scale": tensor_map.pop(f"{name}.pos_scale"),
}
if mode == "asym_uint":
tensors["pos_w_min"] = tensor_map.pop(f"{name}.pos_w_min")
replacement = PackedQuantPatchEmbedder(original, bits, mode, block_size=bs, tensors=tensors)
else:
raise ValueError(f"Unsupported module kind: {kind}")
model.set_submodule(name, replacement)