File size: 10,041 Bytes
05b0ab9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

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