File size: 14,059 Bytes
19d9f3f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 | """Non-uniform column codebooks for ultra-low-bit reference experiments.
These primitives deliberately optimize representation quality, not runtime.
They mirror the column-wise K-means baseline used by recent low-bit Whisper
work and account for codebooks and the mixed-format mask in physical-bpw
figures. A production kernel may choose a different layout after the quality
frontier is established.
"""
from __future__ import annotations
from dataclasses import dataclass
import math
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
def column_codebook_payload_bits(
*,
out_features: int,
in_features: int,
code_bits: int,
centroid_bits: int = 16,
) -> int:
"""Return codes plus one dense codebook per input column."""
if out_features < 1 or in_features < 1:
raise ValueError("matrix dimensions must be positive")
if code_bits < 1 or code_bits > 8:
raise ValueError("code_bits must be in [1, 8]")
if centroid_bits < 1:
raise ValueError("centroid_bits must be positive")
levels = 1 << code_bits
return (
out_features * in_features * code_bits
+ in_features * levels * centroid_bits
)
def column_codebook_physical_bpw(
*,
out_features: int,
code_bits: int,
centroid_bits: int = 16,
) -> float:
"""Physical bpw for column codes and their dense centroid tables."""
return code_bits + (1 << code_bits) * centroid_bits / out_features
def mixed_column_codebook_payload_bits(
q4_mask: torch.Tensor,
*,
out_features: int,
q2_bits: int = 2,
q4_bits: int = 4,
centroid_bits: int = 16,
include_mask: bool = True,
) -> int:
"""Return exact payload bits for a column-wise Q2/Q4 representation."""
if q4_mask.ndim != 1 or q4_mask.dtype != torch.bool:
raise ValueError("q4_mask must be a one-dimensional bool tensor")
if out_features < 1:
raise ValueError("out_features must be positive")
if not 0 < q2_bits < q4_bits <= 8:
raise ValueError("expected 0 < q2_bits < q4_bits <= 8")
if centroid_bits < 1:
raise ValueError("centroid_bits must be positive")
q4_columns = int(q4_mask.sum().item())
q2_columns = q4_mask.numel() - q4_columns
code_bits = out_features * (
q2_columns * q2_bits + q4_columns * q4_bits
)
codebook_bits = centroid_bits * (
q2_columns * (1 << q2_bits) + q4_columns * (1 << q4_bits)
)
mask_bits = q4_mask.numel() if include_mask else 0
return code_bits + codebook_bits + mask_bits
def _weighted_1d_kmeans(
values: torch.Tensor,
weights: torch.Tensor,
*,
levels: int,
iterations: int,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Run deterministic batched weighted one-dimensional K-means.
``values`` and ``weights`` have shape ``[units, samples]``. Quantile
initialization avoids random-seed dependence, while empty clusters retain
their previous centroid.
"""
if values.ndim != 2 or weights.shape != values.shape:
raise ValueError("values and weights must be matching matrices")
if levels < 2 or levels > 256:
raise ValueError("levels must be in [2, 256]")
if values.shape[1] < levels:
raise ValueError("the number of samples must cover every codebook level")
if iterations < 1:
raise ValueError("iterations must be positive")
if torch.any(weights < 0):
raise ValueError("weights must be non-negative")
sorted_values = values.sort(dim=1).values
positions = (
(torch.arange(levels, device=values.device, dtype=torch.float32) + 0.5)
* values.shape[1]
/ levels
).floor().long().clamp_max(values.shape[1] - 1)
centroids = sorted_values.index_select(1, positions)
for _ in range(iterations):
distance = (values.unsqueeze(-1) - centroids.unsqueeze(1)).square()
codes = distance.argmin(-1)
weighted_values = values * weights
numerator = torch.zeros_like(centroids)
denominator = torch.zeros_like(centroids)
numerator.scatter_add_(1, codes, weighted_values)
denominator.scatter_add_(1, codes, weights)
updated = numerator / denominator.clamp_min(1e-20)
centroids = torch.where(denominator > 0, updated, centroids)
centroids = centroids.sort(dim=1).values
distance = (values.unsqueeze(-1) - centroids.unsqueeze(1)).square()
codes = distance.argmin(-1)
reconstructed = centroids.gather(1, codes)
error = (weights * (values - reconstructed).square()).sum(1)
return codes.to(torch.int16), centroids, error
@torch.no_grad()
def weighted_column_codebook_project(
weight: torch.Tensor,
input_second_moment: torch.Tensor,
*,
bits: int = 2,
output_importance: Optional[torch.Tensor] = None,
iterations: int = 12,
chunk_columns: int = 128,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Project each input column into an independent learned codebook.
The returned codes retain the original ``[out, in]`` matrix layout,
centroids have shape ``[in, 2**bits]``, and error is reported per input
column under the diagonal activation/output-importance metric.
"""
if weight.ndim != 2:
raise ValueError("weight must be a matrix")
if bits not in {2, 4}:
raise ValueError("only Q2 and Q4 column codebooks are supported")
if input_second_moment.ndim != 1 or input_second_moment.numel() != weight.shape[1]:
raise ValueError("input_second_moment must match input features")
if chunk_columns < 1:
raise ValueError("chunk_columns must be positive")
if output_importance is None:
output_weight = torch.ones(
weight.shape[0], device=weight.device, dtype=torch.float32
)
else:
if output_importance.ndim != 1 or output_importance.numel() != weight.shape[0]:
raise ValueError("output_importance must match output features")
output_weight = output_importance.detach().to(
device=weight.device, dtype=torch.float32
).clamp_min(0)
values = weight.detach().float().transpose(0, 1).contiguous()
input_weight = input_second_moment.detach().to(
device=weight.device, dtype=torch.float32
).clamp_min(0)
code_chunks = []
centroid_chunks = []
error_chunks = []
levels = 1 << bits
for start in range(0, values.shape[0], chunk_columns):
chunk = values[start : start + chunk_columns]
weights = (
input_weight[start : start + chunk_columns].unsqueeze(1)
* output_weight.unsqueeze(0)
).expand_as(chunk)
codes, centroids, error = _weighted_1d_kmeans(
chunk,
weights,
levels=levels,
iterations=iterations,
)
code_chunks.append(codes)
centroid_chunks.append(centroids)
error_chunks.append(error)
column_codes = torch.cat(code_chunks, dim=0)
code_dtype = torch.int8 if bits <= 4 else torch.int16
return (
column_codes.transpose(0, 1).contiguous().to(code_dtype),
torch.cat(centroid_chunks, dim=0),
torch.cat(error_chunks, dim=0),
)
def reconstruct_column_codebook(
codes: torch.Tensor, centroids: torch.Tensor
) -> torch.Tensor:
"""Materialize a reference weight matrix from column codebooks."""
if codes.ndim != 2 or centroids.ndim != 2:
raise ValueError("codes and centroids must be matrices")
if codes.shape[1] != centroids.shape[0]:
raise ValueError("one codebook is required per input column")
column_codes = codes.long().transpose(0, 1)
if column_codes.numel() and (
int(column_codes.min()) < 0
or int(column_codes.max()) >= centroids.shape[1]
):
raise ValueError("code is outside the centroid table")
return centroids.gather(1, column_codes).transpose(0, 1).contiguous()
def column_outlier_density(
weight: torch.Tensor, *, threshold_multiplier: float = 13.0
) -> torch.Tensor:
"""Measure the fraction of large-magnitude weights in each column."""
if weight.ndim != 2:
raise ValueError("weight must be a matrix")
if threshold_multiplier <= 0:
raise ValueError("threshold_multiplier must be positive")
value = weight.detach().float().abs()
threshold = (
value.mean(0).clamp_min(torch.finfo(value.dtype).tiny)
* float(threshold_multiplier)
)
return (value > threshold.unsqueeze(0)).float().mean(0)
@dataclass(frozen=True)
class MixedColumnCodebookProjection:
codes: torch.Tensor
q2_centroids: torch.Tensor
q4_centroids: torch.Tensor
q4_mask: torch.Tensor
column_error: torch.Tensor
payload_bits: int
physical_bpw: float
selection: str
def effective_weight(self) -> torch.Tensor:
q2 = reconstruct_column_codebook(self.codes.clamp_max(3), self.q2_centroids)
q4 = reconstruct_column_codebook(self.codes, self.q4_centroids)
return torch.where(self.q4_mask.unsqueeze(0), q4, q2)
@torch.no_grad()
def mixed_column_codebook_project(
weight: torch.Tensor,
input_second_moment: torch.Tensor,
*,
q4_fraction: float = 0.05,
output_importance: Optional[torch.Tensor] = None,
outlier_threshold_multiplier: float = 13.0,
iterations: int = 12,
chunk_columns: int = 128,
centroid_bits: int = 16,
selection: str = "outlier",
) -> MixedColumnCodebookProjection:
"""Use Q4 on selected columns and learned Q2 elsewhere.
``outlier`` reproduces the inexpensive column-density heuristic from
ultra-low-bit Whisper PTQ. ``error_gain`` is a calibration-aware
rate--distortion oracle: it promotes columns with the largest measured
Q2-to-Q4 reduction under the declared diagonal metric.
"""
if not 0.0 <= q4_fraction <= 1.0:
raise ValueError("q4_fraction must be in [0, 1]")
if selection not in {"outlier", "error_gain"}:
raise ValueError("selection must be outlier or error_gain")
q2_codes, q2_centroids, q2_error = weighted_column_codebook_project(
weight,
input_second_moment,
bits=2,
output_importance=output_importance,
iterations=iterations,
chunk_columns=chunk_columns,
)
q4_codes, q4_centroids, q4_error = weighted_column_codebook_project(
weight,
input_second_moment,
bits=4,
output_importance=output_importance,
iterations=iterations,
chunk_columns=chunk_columns,
)
count = int(math.floor(weight.shape[1] * q4_fraction + 0.5))
q4_mask = torch.zeros(
weight.shape[1], device=weight.device, dtype=torch.bool
)
if count:
if selection == "outlier":
score = column_outlier_density(
weight, threshold_multiplier=outlier_threshold_multiplier
)
else:
score = q2_error - q4_error
# Stable index tie-break keeps all artifacts reproducible.
order = torch.argsort(score, descending=True, stable=True)
q4_mask[order[:count]] = True
codes = torch.where(q4_mask.unsqueeze(0), q4_codes, q2_codes)
error = torch.where(q4_mask, q4_error, q2_error)
payload = mixed_column_codebook_payload_bits(
q4_mask,
out_features=weight.shape[0],
centroid_bits=centroid_bits,
)
return MixedColumnCodebookProjection(
codes=codes,
q2_centroids=q2_centroids,
q4_centroids=q4_centroids,
q4_mask=q4_mask,
column_error=error,
payload_bits=payload,
physical_bpw=payload / weight.numel(),
selection=selection,
)
class FixedColumnCodebookLinear(nn.Module):
"""Reference evaluation layer backed by materialized column codebooks."""
def __init__(
self,
codes: torch.Tensor,
centroids: torch.Tensor,
*,
bias: Optional[torch.Tensor] = None,
compute_dtype: torch.dtype = torch.float32,
):
super().__init__()
weight = reconstruct_column_codebook(codes, centroids)
self.register_buffer("_evaluation_weight", weight.to(compute_dtype))
if bias is None:
self.bias = None
else:
self.register_buffer("bias", bias.detach().to(compute_dtype).clone())
self.in_features = int(weight.shape[1])
self.out_features = int(weight.shape[0])
self.compute_dtype = compute_dtype
def effective_weight(self) -> torch.Tensor:
return self._evaluation_weight
def forward(self, value: torch.Tensor) -> torch.Tensor:
bias = None if self.bias is None else self.bias.to(value.dtype)
return F.linear(value, self._evaluation_weight.to(value.dtype), bias)
class FixedMixedColumnCodebookLinear(nn.Module):
"""Reference evaluation layer for outlier-selected Q2/Q4 columns."""
def __init__(
self,
projection: MixedColumnCodebookProjection,
*,
bias: Optional[torch.Tensor] = None,
compute_dtype: torch.dtype = torch.float32,
):
super().__init__()
weight = projection.effective_weight()
self.register_buffer("_evaluation_weight", weight.to(compute_dtype))
self.register_buffer("q4_mask", projection.q4_mask.detach().clone())
if bias is None:
self.bias = None
else:
self.register_buffer("bias", bias.detach().to(compute_dtype).clone())
self.in_features = int(weight.shape[1])
self.out_features = int(weight.shape[0])
self.compute_dtype = compute_dtype
self.payload_bits = int(projection.payload_bits)
self.physical_bpw = float(projection.physical_bpw)
def effective_weight(self) -> torch.Tensor:
return self._evaluation_weight
def forward(self, value: torch.Tensor) -> torch.Tensor:
bias = None if self.bias is None else self.bias.to(value.dtype)
return F.linear(value, self._evaluation_weight.to(value.dtype), bias)
|