File size: 11,199 Bytes
8c16eba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
"""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)