hsaq-tools / quantization /hsaq /assignment.py
mxguru1's picture
AWQ POC supporting code + runners 2026-05-20
05b0ab9 verified
"""
Sovereign Hive β€” Bit-width assignment for HSAQ quantization.
Given per-layer drift measurements at each (bits, quantizer) combination,
selects a (bits, quantizer) assignment per layer that minimizes total drift
subject to a global VRAM-weights budget.
Pure logic β€” no I/O. Input data comes from sensitivity_profile rows fetched
by the caller via the Vault module (which sits behind PermissionGate).
Algorithm: greedy by drift-savings-per-byte-cost.
1. Start: every layer assigned its cheapest option.
2. While budget allows: globally pick the (layer, upgrade) pair that
buys the most drift reduction per additional byte; apply it.
3. Stop: when no upgrade fits the remaining budget, or no upgrade
reduces drift further.
Provably within a small constant factor of the ILP optimum for this shape of
problem; runs in O(L * B^2) per pass and converges in at most L*(B-1) passes,
where L = number of layer/components and B = bit-width options. Milliseconds
for any realistic model. The pattern is standard in SqueezeLLM and OWQ.
For multi-config output (a Pareto frontier per candidate), call pareto_frontier
with a list of budgets.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Literal
Quantizer = Literal["hqq", "awq", "gptq"]
BitWidth = Literal[2, 3, 4]
# ── Inputs / outputs ───────────────────────────────────────────────────────
@dataclass(frozen=True)
class LayerOption:
"""One (bits, quantizer) candidate for a layer/component.
bytes_per_param should already include quantizer-specific overhead
(HQQ group-quant scales/zeros, AWQ/GPTQ metadata, etc.); the profiler
is responsible for measuring it accurately.
"""
bits: BitWidth
quantizer: Quantizer
drift: float # measured KL divergence vs fp16
bytes_per_param: float # bits/8 + quantizer overhead
@dataclass
class LayerCandidate:
"""All measured options for a single layer/component."""
layer_idx: int
component: str # 'attn' | 'mlp' | 'attn.q' | 'attn.k' | ...
param_count: int # in this layer/component
options: list[LayerOption]
def cheapest(self) -> LayerOption:
"""Option with the smallest bytes_per_param."""
return min(self.options, key=lambda o: o.bytes_per_param)
@dataclass
class Assignment:
layer_idx: int
component: str
chosen: LayerOption
bytes_used: float
@dataclass
class AssignmentResult:
assignments: list[Assignment]
total_drift: float
total_weights_gb: float
budget_gb: float
headroom_gb: float
saturated: bool # True if budget filled before all upgrades exhausted
@property
def by_layer(self) -> dict[tuple[int, str], Assignment]:
return {(a.layer_idx, a.component): a for a in self.assignments}
class BudgetInfeasibleError(Exception):
def __init__(self, current_gb: float, budget_gb: float):
super().__init__(
f"Even the cheapest assignment ({current_gb:.2f} GB) exceeds the "
f"weight budget ({budget_gb:.2f} GB). Reduce model size, increase "
f"KV quantization aggressiveness, or shrink context length."
)
self.current_gb = current_gb
self.budget_gb = budget_gb
# ── Core algorithm ─────────────────────────────────────────────────────────
def assign_bit_widths(
candidates: list[LayerCandidate],
weight_budget_gb: float,
min_bits_floor: dict[str, int] | None = None,
) -> AssignmentResult:
"""Greedy assignment of (bits, quantizer) per layer/component.
Parameters
----------
candidates : list[LayerCandidate]
One entry per layer/component, each carrying its measured options
from the sensitivity_profile Vault table.
weight_budget_gb : float
Maximum total weight VRAM in GB. Caller computes this by subtracting
KV cache, activations, LoRA, and driver headroom from VRAM_BUDGET_GB.
min_bits_floor : dict[str, int] | None
Optional per-component lower bound on bit width. Maps component name
(LayerCandidate.component) -> minimum bits. Layers in this dict will
start at the cheapest option meeting the floor, which sidesteps HQQ's
non-monotonic-drift filter on outlier-heavy layers (those where
4-bit drift can exceed 3-bit drift due to group-quant breaking on
outlier channels). The greedy loop never downgrades, so the floor
is preserved through to the final assignment.
Raises
------
BudgetInfeasibleError
If even the cheapest assignment (respecting the floor) exceeds budget.
ValueError
If a floor specifies a layer with no option meeting it.
"""
if not candidates:
raise ValueError("No candidates provided")
if weight_budget_gb <= 0:
raise ValueError(f"Non-positive weight budget: {weight_budget_gb}")
floor = min_bits_floor or {}
def _cheapest_meeting_floor(c: LayerCandidate) -> LayerOption:
min_bits = floor.get(c.component)
if min_bits is None:
return c.cheapest()
eligible = [o for o in c.options if o.bits >= min_bits]
if not eligible:
raise ValueError(
f"No option for layer '{c.component}' meets floor {min_bits}-bit "
f"(available: {sorted({o.bits for o in c.options})})"
)
return min(eligible, key=lambda o: o.bytes_per_param)
# Initialize at the cheapest option per layer (respecting floor).
current: dict[tuple[int, str], LayerOption] = {}
bytes_used: dict[tuple[int, str], float] = {}
cand_by_key: dict[tuple[int, str], LayerCandidate] = {}
for c in candidates:
key = (c.layer_idx, c.component)
opt = _cheapest_meeting_floor(c)
current[key] = opt
bytes_used[key] = opt.bytes_per_param * c.param_count
cand_by_key[key] = c
total_bytes = sum(bytes_used.values())
budget_bytes = weight_budget_gb * 1e9
if total_bytes > budget_bytes:
raise BudgetInfeasibleError(
current_gb=total_bytes / 1e9,
budget_gb=weight_budget_gb,
)
def best_upgrade(key: tuple[int, str]) -> tuple[float, LayerOption, float] | None:
"""Return (drift_savings_per_byte, target_option, extra_bytes) for the
best upgrade of this layer, or None if no upgrade is available."""
cand = cand_by_key[key]
cur = current[key]
best: tuple[float, LayerOption, float] | None = None
for opt in cand.options:
if opt.bytes_per_param <= cur.bytes_per_param:
continue
if opt.drift >= cur.drift:
continue # not actually an upgrade
drift_reduction = cur.drift - opt.drift
extra_bytes = (opt.bytes_per_param - cur.bytes_per_param) * cand.param_count
if extra_bytes <= 0:
continue
ratio = drift_reduction / extra_bytes
if best is None or ratio > best[0]:
best = (ratio, opt, extra_bytes)
return best
saturated = False
while True:
winner_key: tuple[int, str] | None = None
winner_ratio = -1.0
winner_opt: LayerOption | None = None
winner_extra = 0.0
any_upgrade_available = False
for key in current:
up = best_upgrade(key)
if up is None:
continue
any_upgrade_available = True
_ratio, target, extra = up
if total_bytes + extra > budget_bytes:
continue
if _ratio > winner_ratio:
winner_ratio = _ratio
winner_key = key
winner_opt = target
winner_extra = extra
if winner_key is None:
saturated = any_upgrade_available
break
# Apply winning upgrade.
assert winner_opt is not None
bytes_used[winner_key] += winner_extra
total_bytes += winner_extra
current[winner_key] = winner_opt
assignments = [
Assignment(
layer_idx=key[0],
component=key[1],
chosen=current[key],
bytes_used=bytes_used[key],
)
for key in current
]
assignments.sort(key=lambda a: (a.layer_idx, a.component))
total_drift = sum(a.chosen.drift for a in assignments)
total_weights_gb = total_bytes / 1e9
return AssignmentResult(
assignments=assignments,
total_drift=total_drift,
total_weights_gb=total_weights_gb,
budget_gb=weight_budget_gb,
headroom_gb=weight_budget_gb - total_weights_gb,
saturated=saturated,
)
# ── Pareto frontier exploration ────────────────────────────────────────────
def pareto_frontier(
candidates: list[LayerCandidate],
budgets_gb: list[float],
) -> list[AssignmentResult]:
"""Run assign_bit_widths at multiple budgets to produce a Pareto frontier
(budget vs total_drift). Caller picks the knee point or surfaces the
trade-off to a human reviewer.
Infeasible budgets are skipped (not raised) so a partial frontier is still
useful when the lower budgets are too tight.
"""
results: list[AssignmentResult] = []
for b in budgets_gb:
try:
results.append(assign_bit_widths(candidates, b))
except BudgetInfeasibleError:
continue
return results