hsaq-tools / quantization /hsaq /candidate_record.py
mxguru1's picture
AWQ POC supporting code + runners 2026-05-20
05b0ab9 verified
"""
Sovereign Hive — Model Hunter Candidate Record
Pure-data module. No I/O, no Vault access, no network. All persistence happens
through the Vault module, which routes through PermissionGate.
Convention: this file MUST NOT import sqlite3, requests, httpx, os, pathlib,
subprocess, or socket. If it ever needs to, that's a signal the logic belongs
in the Vault module or the hunter agent, not here.
"""
from __future__ import annotations
from dataclasses import asdict, dataclass, field
from datetime import UTC, datetime
from enum import StrEnum
from typing import Literal
# ---------------------------------------------------------------------------
# Enums
# ---------------------------------------------------------------------------
class ArchType(StrEnum):
MHA = "MHA"
GQA = "GQA"
MQA = "MQA"
class EligibilityTier(StrEnum):
GREEN = "green" # fits comfortably, ready to profile/quantize
YELLOW = "yellow" # fits but tight, or constrained on pruning/tokenizer
RED = "red" # should not have survived filter; diagnostic only
# ---------------------------------------------------------------------------
# VRAM prediction constants & helpers
# ---------------------------------------------------------------------------
# These should ideally be sourced from project config. Kept here as the
# reference implementation that matches the HSAQ spec.
HSAQ_TIER_SPLIT = (0.30, 0.40, 0.30) # critical, normal, tolerant
HSAQ_TIER_BITS = (4, 3, 3) # 2-bit floor opt-in only — keep at 3
HQQ_OVERHEAD_FACTOR = 0.07 # group-quant scales + zeros, ~5-8%
LORA_RANK_16_GB = 0.05 # rank-16 adapter on a 20B-class model
ACTIVATIONS_GB_4K = 0.8 # batch=1, ctx=4k, generous
VRAM_BUDGET_GB = 12.0 # RTX 5070
VRAM_DRIVER_HEADROOM_GB = 0.5 # OS/driver reserve
MAX_REALISTIC_PARAM_COUNT = 22_000_000_000
def predicted_avg_bits() -> float:
return sum(s * b for s, b in zip(HSAQ_TIER_SPLIT, HSAQ_TIER_BITS, strict=False))
def predict_weights_gb(param_count: int) -> float:
"""Mixed 3/4-bit weights at HSAQ default tier split, with HQQ overhead."""
raw = (param_count * predicted_avg_bits() / 8) / 1e9
return raw * (1 + HQQ_OVERHEAD_FACTOR)
def predict_kv_gb(
num_kv_heads: int,
head_dim: int,
num_layers: int,
context_length: int = 4096,
bytes_per_element: int = 1, # int8 KV by default
) -> float:
"""KV cache size in GB at a given context length and precision."""
bytes_per_token = 2 * num_kv_heads * head_dim * num_layers * bytes_per_element
return (bytes_per_token * context_length) / 1e9
# ---------------------------------------------------------------------------
# CandidateRecord
# ---------------------------------------------------------------------------
@dataclass
class CandidateRecord:
# --- Identity ---
model_id: str
model_hash: str
source: Literal["hf_hub", "local_mirror", "manual"]
discovered_at: datetime
# --- Architecture ---
arch_type: ArchType
param_count: int
hidden_size: int
num_layers: int
num_attention_heads: int
num_kv_heads: int
head_dim: int
max_position_embeddings: int
# --- License & compat ---
license: str
license_commercial_ok: bool
tokenizer_family: str
tokenizer_compat_score: float
# --- Provenance (audit chain) ---
discovered_by_agent_id: str
discovered_by_agent_tier: int
# --- Sensitivity priors (skip the 30-min pass if these exist) ---
has_published_sensitivity_profile: bool = False
published_profile_source: str | None = None
# --- Computed fields (filled by __post_init__ / refresh_predictions) ---
kv_bytes_per_token_fp16: int = 0
kv_bytes_per_token_int8: int = 0
predicted_vram_weights_mixed_34: float = 0.0
predicted_vram_kv_4k_int8: float = 0.0
predicted_vram_total_4k: float = 0.0
predicted_headroom_gb: float = 0.0
pruning_eligible: bool = False
pruning_eligible_reason: str = ""
hsaq_eligibility: EligibilityTier = EligibilityTier.RED
eligibility_reasons: list[str] = field(default_factory=list)
def __post_init__(self) -> None:
self.refresh_predictions()
# -- Predictions ---------------------------------------------------------
def refresh_predictions(self) -> None:
"""Recompute all derived fields. Idempotent."""
self.kv_bytes_per_token_fp16 = 2 * self.num_kv_heads * self.head_dim * self.num_layers * 2
self.kv_bytes_per_token_int8 = self.kv_bytes_per_token_fp16 // 2
self.predicted_vram_weights_mixed_34 = predict_weights_gb(self.param_count)
self.predicted_vram_kv_4k_int8 = predict_kv_gb(
num_kv_heads=self.num_kv_heads,
head_dim=self.head_dim,
num_layers=self.num_layers,
context_length=4096,
bytes_per_element=1,
)
self.predicted_vram_total_4k = (
self.predicted_vram_weights_mixed_34 + self.predicted_vram_kv_4k_int8 + LORA_RANK_16_GB + ACTIVATIONS_GB_4K
)
self.predicted_headroom_gb = VRAM_BUDGET_GB - VRAM_DRIVER_HEADROOM_GB - self.predicted_vram_total_4k
self._compute_pruning_eligibility()
self._compute_eligibility()
def _compute_pruning_eligibility(self) -> None:
# Default: pruning OFF for GQA/MQA. The published literature on safe
# head pruning is MHA-centric; GQA/MQA share KV heads across query
# heads and structured pruning needs separate validation per arch.
if self.arch_type is ArchType.MHA:
self.pruning_eligible = True
self.pruning_eligible_reason = "MHA arch — head pruning literature applies"
else:
self.pruning_eligible = False
self.pruning_eligible_reason = (
f"{self.arch_type.value} arch — head pruning off by default; shared KV heads need separate validation"
)
def _compute_eligibility(self) -> None:
reasons: list[str] = []
tier = EligibilityTier.GREEN
# ----- Hard fails (RED) -----
if self.predicted_headroom_gb < 0:
reasons.append(
f"OOM predicted: total {self.predicted_vram_total_4k:.2f} GB "
f"exceeds usable {VRAM_BUDGET_GB - VRAM_DRIVER_HEADROOM_GB:.2f} GB"
)
tier = EligibilityTier.RED
if not self.license_commercial_ok:
reasons.append(f"License '{self.license}' not commercial-compatible")
tier = EligibilityTier.RED
if self.tokenizer_compat_score < 0.6:
reasons.append(f"Tokenizer compat {self.tokenizer_compat_score:.2f} < 0.6")
tier = EligibilityTier.RED
if self.param_count > MAX_REALISTIC_PARAM_COUNT:
reasons.append(f"Param count {self.param_count:,} above realistic ceiling ({MAX_REALISTIC_PARAM_COUNT:,})")
tier = EligibilityTier.RED
if tier is EligibilityTier.RED:
self.hsaq_eligibility = tier
self.eligibility_reasons = reasons
return
# ----- Soft constraints (downgrade GREEN -> YELLOW) -----
if self.predicted_headroom_gb < 1.0:
reasons.append(
f"Tight headroom: {self.predicted_headroom_gb:.2f} GB free after "
"predicted load; long-context use likely to OOM"
)
tier = EligibilityTier.YELLOW
if self.arch_type is ArchType.MHA:
reasons.append("MHA arch — larger KV cache than GQA equivalents")
if tier is EligibilityTier.GREEN:
tier = EligibilityTier.YELLOW
if 0.6 <= self.tokenizer_compat_score < 0.85:
reasons.append(f"Tokenizer compat {self.tokenizer_compat_score:.2f} below 0.85")
if tier is EligibilityTier.GREEN:
tier = EligibilityTier.YELLOW
if tier is EligibilityTier.GREEN and not reasons:
reasons.append("All checks passed at green threshold")
self.hsaq_eligibility = tier
self.eligibility_reasons = reasons
# -- Serialization -------------------------------------------------------
# The Vault module owns the INSERT/SELECT. These helpers just produce
# and consume row-shaped dicts. Vault writes go through PermissionGate
# and include originating agent_id + tier on every row.
def to_vault_payload(self) -> dict:
d = asdict(self)
d["arch_type"] = self.arch_type.value
d["hsaq_eligibility"] = self.hsaq_eligibility.value
d["discovered_at"] = self.discovered_at.astimezone(UTC).isoformat()
# eligibility_reasons stays as list — Vault module is responsible for
# JSON-encoding on insert and decoding on select.
return d
@classmethod
def from_vault_row(cls, row: dict) -> CandidateRecord:
row = dict(row) # shallow copy — don't mutate caller's row
row["arch_type"] = ArchType(row["arch_type"])
row["hsaq_eligibility"] = EligibilityTier(row["hsaq_eligibility"])
if isinstance(row["discovered_at"], str):
row["discovered_at"] = datetime.fromisoformat(row["discovered_at"])
return cls(**row)