hsaq-tools / quantization /hsaq /candidate.py
mxguru1's picture
AWQ POC supporting code + runners 2026-05-20
05b0ab9 verified
"""
HSAQ Model Hunter β€” Candidate Discovery, Filter, Score, and Emit
=================================================================
The 5-stage model hunter pipeline:
Stage 1 β€” DISCOVERY: Pull candidates from HF Hub, local mirrors
Stage 2 β€” FILTER: Kill fast (license, VRAM, tokenizer, arch, param cap)
Stage 3 β€” SCORE: Composite ranking (headroom, benchmarks, compat, arch)
Stage 4 β€” PROFILE: Sensitivity profiling top-N (delegates to HSAQPipeline)
Stage 5 β€” EMIT: Final eligibility (green / yellow / red)
Stages 1-3 and 5 are pure computation, no GPU needed.
Stage 4 is VRAM-heavy and escalates through the inference queue.
"""
from __future__ import annotations
import hashlib
import json
import logging
import time
from dataclasses import dataclass, field
from datetime import UTC, datetime
from pathlib import Path
from quantization.hsaq.config import (
ACTIVATION_OVERHEAD_GB,
DEFAULT_GPU_BUDGET_GB,
HQQ_OVERHEAD_FACTOR,
KV_CACHE_4K_FP16_GB,
KV_CACHE_4K_INT8_GB,
LORA_BUDGET_GB,
SAFE_HEADROOM_GB,
ArchType,
HSAQConfig,
HSAQEligibility,
)
logger = logging.getLogger("HSAQ.Hunter")
PIPELINE_VERSION = "1.0.0" # bump on algo changes to invalidate caches
# ── Candidate Record ───────────────────────────────────────────────────────
@dataclass
class CandidateRecord:
"""Complete candidate record emitted by the model hunter.
Fields populated at each stage:
Stage 1 (discovery): model_id, model_hash, discovered_at, source, arch fields
Stage 2 (filter): license fields, predicted VRAM fields, tokenizer_compat_score
Stage 3 (score): composite_score, rank
Stage 4 (profile): has_published_sensitivity_profile, sensitivity tiers
Stage 5 (emit): hsaq_eligibility, eligibility_reasons
"""
# ── Identity ──────────────────────────────────────────────────────────
model_id: str # e.g. "Qwen/Qwen2.5-14B-Instruct"
model_hash: str # sha256 of config + tokenizer + weight manifest
discovered_at: datetime
source: str # "hf_hub" | "local_mirror" | "manual"
# ── Architecture ───────────────────────────────────────────────────────
arch_type: ArchType
param_count: int # total, not "active" for MoE
hidden_size: int
num_layers: int
num_attention_heads: int
num_kv_heads: int # critical for KV cache math
head_dim: int
max_position_embeddings: int
# ── KV cache math ─────────────────────────────────────────────────────
kv_bytes_per_token_fp16: int # 2 * num_kv_heads * head_dim * num_layers
kv_bytes_per_token_int8: int # half of above
# ── Licensing & compat ─────────────────────────────────────────────────
license: str = ""
license_commercial_ok: bool = True
tokenizer_family: str = "" # "llama" | "qwen" | "mistral" | etc
tokenizer_compat_score: float = 0.0 # vs calibration set, 0-1
# ── HSAQ predictions (computed, not measured) ─────────────────────────
predicted_vram_weights_mixed_34: float = 0.0 # GB, with HQQ overhead
predicted_vram_kv_4k_int8: float = 0.0 # GB at 4K ctx, int8 KV
predicted_vram_kv_4k_fp16: float = 0.0 # GB at 4K ctx, fp16 KV
predicted_vram_total_4k: float = 0.0 # weights + kv + activations + lora + headroom
predicted_headroom_gb: float = 0.0 # DEFAULT_GPU_BUDGET_GB - total
# ── Sensitivity priors ─────────────────────────────────────────────────
has_published_sensitivity_profile: bool = False
published_profile_source: str | None = None # paper/repo URL
# ── Eligibility ────────────────────────────────────────────────────────
hsaq_eligibility: HSAQEligibility = "red"
eligibility_reasons: list[str] = field(default_factory=list)
# ── Pruning gate ───────────────────────────────────────────────────────
pruning_eligible: bool = False
pruning_eligible_reason: str = ""
# ── Scoring ────────────────────────────────────────────────────────────
composite_score: float = 0.0
rank: int = -1
# ── VRAM Prediction ────────────────────────────────────────────────────────
def predict_vram_mixed_34bit(
param_count: int,
num_kv_heads: int,
head_dim: int,
num_layers: int,
*,
ctx_len: int = 4096,
kv_bits: int = 8,
critical_frac: float = 0.30,
normal_frac: float = 0.40,
tolerant_frac: float = 0.30,
) -> dict[str, float]:
"""Predict VRAM usage for a candidate at mixed 3/4-bit.
Formula:
avg_bits = critical_frac * 4 + normal_frac * 3 + tolerant_frac * 3
weights_gb = (param_count * avg_bits / 8) / 1e9
hqq_overhead = weights_gb * (HQQ_OVERHEAD_FACTOR - 1.0)
kv_gb = _kv_cache_gb(num_kv_heads, head_dim, num_layers, ctx_len, kv_bits)
total = weights_gb + hqq_overhead + kv_gb + LORA_BUDGET_GB + ACTIVATION_OVERHEAD_GB + SAFE_HEADROOM_GB
"""
avg_bits = critical_frac * 4 + normal_frac * 3 + tolerant_frac * 3
weights_gb = (param_count * avg_bits / 8) / 1e9
hqq_overhead_gb = weights_gb * (HQQ_OVERHEAD_FACTOR - 1.0)
kv_gb = _kv_cache_gb(num_kv_heads, head_dim, num_layers, ctx_len, kv_bits)
total = weights_gb + hqq_overhead_gb + kv_gb + LORA_BUDGET_GB + ACTIVATION_OVERHEAD_GB + SAFE_HEADROOM_GB
headroom = DEFAULT_GPU_BUDGET_GB - total
return {
"weights_gb": round(weights_gb, 3),
"hqq_overhead_gb": round(hqq_overhead_gb, 3),
"kv_gb": round(kv_gb, 3),
"lora_gb": LORA_BUDGET_GB,
"activations_gb": ACTIVATION_OVERHEAD_GB,
"headroom_gb": SAFE_HEADROOM_GB,
"total_gb": round(total, 3),
"predicted_headroom_gb": round(headroom, 3),
"avg_bits": round(avg_bits, 2),
}
def _kv_cache_gb(
num_kv_heads: int,
head_dim: int,
num_layers: int,
ctx_len: int,
kv_bits: int,
) -> float:
"""KV cache size in GB for given context length."""
bytes_per_token = kv_bits // 8 * num_kv_heads * head_dim * num_layers
total_bytes = bytes_per_token * ctx_len * 2 # *2 for K + V caches
return total_bytes / 1e9
def kv_bytes_per_token(
num_kv_heads: int,
head_dim: int,
num_layers: int,
kv_bits: int = 16,
) -> int:
"""Per-token KV cache bytes (K + V)."""
return kv_bits // 8 * num_kv_heads * head_dim * num_layers * 2
# ── Architecture Extraction ────────────────────────────────────────────────
def extract_arch_from_config(config: dict) -> dict:
"""Extract architecture fields from a HuggingFace model config.json."""
arch_type: ArchType = "MHA"
num_kv_heads = config.get("num_key_value_heads", config.get("num_attention_heads", 0))
if num_kv_heads and num_kv_heads < config.get("num_attention_heads", 0):
arch_type = "GQA"
if num_kv_heads == 1:
arch_type = "MQA"
return {
"arch_type": arch_type,
"param_count": 0, # filled from model metadata, not config.json alone
"hidden_size": config.get("hidden_size", 0),
"num_layers": config.get("num_hidden_layers", config.get("n_layer", 0)),
"num_attention_heads": config.get("num_attention_heads", 0),
"num_kv_heads": num_kv_heads,
"head_dim": config.get(
"head_dim",
config.get("hidden_size", 0) // max(config.get("num_attention_heads", 1), 1),
),
"max_position_embeddings": config.get("max_position_embeddings", 4096),
}
def compute_model_hash(model_id: str, config: dict) -> str:
"""Deterministic hash from model_id + config for cache keys."""
payload = json.dumps({"model_id": model_id, "config_keys": sorted(config.keys())}, sort_keys=True)
return hashlib.sha256(payload.encode()).hexdigest()[:16]
# ── Discovery Stage ────────────────────────────────────────────────────────
class DiscoveryStage:
"""Stage 1: Pull candidates from configured sources. Cheap, no inference."""
def discover_from_hf(
self,
queries: list[str],
*,
limit_per_query: int = 10,
hf_token: str | None = None,
) -> list[CandidateRecord]:
"""Discover models from HuggingFace Hub matching queries.
Args:
queries: Search queries like ["llama-3", "qwen2.5", "mistral"]
limit_per_query: Max candidates per query
hf_token: Optional HF API token
Returns:
List of CandidateRecords with identity + arch fields populated
"""
from huggingface_hub import HfApi
api = HfApi(token=hf_token)
models: list[CandidateRecord] = []
seen: set[str] = set()
now = datetime.now(UTC)
for query in queries:
try:
results = list(
api.list_models(
search=query,
sort="downloads",
direction=-1,
limit=limit_per_query * 2, # over-fetch; filter dedup below
full=False,
)
)
except Exception as exc:
logger.warning("HF search failed for '%s': %s", query, exc)
continue
for model_info in results:
model_id = model_info.modelId
if model_id in seen:
continue
seen.add(model_id)
try:
candidate = self._build_candidate(model_id, model_info, now, api)
if candidate is not None:
models.append(candidate)
except Exception as exc:
logger.debug("Skipping %s: %s", model_id, exc)
continue
if len(models) >= limit_per_query:
break
logger.info("Discovery: %d candidates from %d queries", len(models), len(queries))
return models
def _build_candidate(
self,
model_id: str,
model_info,
discovered_at: datetime,
api,
) -> CandidateRecord | None:
"""Build a CandidateRecord from HF model info."""
# Fetch config
try:
config = api.model_info(model_id, files_metadata=True)
config_bytes = None
for sibling in getattr(config, "siblings", []):
if sibling.rfilename == "config.json":
from huggingface_hub import hf_hub_download
config_path = hf_hub_download(model_id, "config.json")
config_bytes = Path(config_path).read_bytes()
break
except Exception:
logger.debug("Cannot fetch config for %s", model_id)
return None
if config_bytes is None:
return None
config_dict = json.loads(config_bytes)
arch = extract_arch_from_config(config_dict)
# Skip models with missing critical arch info
if arch["num_layers"] == 0 or arch["num_attention_heads"] == 0:
logger.debug("Skipping %s: incomplete arch info", model_id)
return None
model_hash = compute_model_hash(model_id, config_dict)
# Compute KV cache sizes
kv_fp16 = kv_bytes_per_token(arch["num_kv_heads"], arch["head_dim"], arch["num_layers"], 16)
kv_int8 = kv_bytes_per_token(arch["num_kv_heads"], arch["head_dim"], arch["num_layers"], 8)
# Predict VRAM β€” use safetensors total if available, else fall back
st = model_info.safetensors if hasattr(model_info, "safetensors") else None
param_est = st.get("total", 0) if st else arch.get("param_count", 0)
vram = predict_vram_mixed_34bit(
param_count=param_est,
num_kv_heads=arch["num_kv_heads"],
head_dim=arch["head_dim"],
num_layers=arch["num_layers"],
)
return CandidateRecord(
model_id=model_id,
model_hash=model_hash,
discovered_at=discovered_at,
source="hf_hub",
arch_type=arch["arch_type"],
param_count=arch.get("param_count", 0),
hidden_size=arch["hidden_size"],
num_layers=arch["num_layers"],
num_attention_heads=arch["num_attention_heads"],
num_kv_heads=arch["num_kv_heads"],
head_dim=arch["head_dim"],
max_position_embeddings=arch["max_position_embeddings"],
kv_bytes_per_token_fp16=kv_fp16,
kv_bytes_per_token_int8=kv_int8,
license=getattr(model_info, "license", "") or "",
tokenizer_family=_guess_tokenizer_family(model_id),
predicted_vram_weights_mixed_34=vram["weights_gb"] + vram["hqq_overhead_gb"],
predicted_vram_kv_4k_int8=KV_CACHE_4K_INT8_GB,
predicted_vram_kv_4k_fp16=KV_CACHE_4K_FP16_GB,
predicted_vram_total_4k=vram["total_gb"],
predicted_headroom_gb=vram["predicted_headroom_gb"],
)
def _guess_tokenizer_family(model_id: str) -> str:
"""Guess tokenizer family from model ID."""
lower = model_id.lower()
if "llama" in lower:
return "llama"
if "qwen" in lower:
return "qwen"
if "mistral" in lower:
return "mistral"
if "deepseek" in lower:
return "deepseek"
if "phi" in lower:
return "phi"
if "gemma" in lower:
return "gemma"
if "falcon" in lower:
return "falcon"
return "unknown"
# ── Filter Stage ───────────────────────────────────────────────────────────
@dataclass
class FilterConfig:
"""Configuration for the filter stage."""
require_commercial_license: bool = True
max_param_count: int = 22_000_000_000 # 22B ceiling
min_tokenizer_compat: float = 0.6
max_vram_total_4k_gb: float = 11.5 # leave 500 MB OS/driver
exclude_archs: list[str] = field(default_factory=list) # unsupported archs
class FilterStage:
"""Stage 2: Kill candidates that fail any filter. Pure computation."""
def __init__(self, config: FilterConfig):
self.config = config
def filter(self, candidates: list[CandidateRecord]) -> list[CandidateRecord]:
"""Apply all filters. Returns survivors."""
survivors: list[CandidateRecord] = []
for candidate in candidates:
reasons: list[str] = []
# License
if self.config.require_commercial_license and not candidate.license_commercial_ok:
reasons.append("license: non-commercial")
# VRAM
if candidate.predicted_vram_total_4k > self.config.max_vram_total_4k_gb:
reasons.append(
f"vram: {candidate.predicted_vram_total_4k:.1f} GB > {self.config.max_vram_total_4k_gb} GB"
)
# Tokenizer compat
if candidate.tokenizer_compat_score < self.config.min_tokenizer_compat:
reasons.append(
f"tokenizer_compat: {candidate.tokenizer_compat_score:.2f} < {self.config.min_tokenizer_compat}"
)
# Architecture support
if candidate.arch_type in self.config.exclude_archs:
reasons.append(f"arch: {candidate.arch_type} excluded")
# Param cap
if candidate.param_count > self.config.max_param_count:
reasons.append(f"param_count: {candidate.param_count:,} > {self.config.max_param_count:,}")
if reasons:
logger.info("FILTERED %s: %s", candidate.model_id, "; ".join(reasons))
continue
# Pruning gate
candidate.pruning_eligible = candidate.arch_type == "MHA"
if not candidate.pruning_eligible:
candidate.pruning_eligible_reason = (
f"GQA/MQA models not eligible for head pruning (arch_type={candidate.arch_type})"
)
survivors.append(candidate)
logger.info(
"Filter: %d/%d survived (killed %d)",
len(survivors),
len(candidates),
len(candidates) - len(survivors),
)
return survivors
# ── Score Stage ────────────────────────────────────────────────────────────
class ScoreStage:
"""Stage 3: Rank survivors by composite score.
Scoring dimensions (all 0-1, linearly combined):
- headroom_score: more headroom is better (up to 2 GB, then plateaus)
- arch_score: GQA preferred (cheaper KV cache), MHA neutral, MQA slight penalty
- tokenizer_score: compatibility with calibration set
- published_score: bonus if sensitivity profile already exists
"""
def score(self, candidates: list[CandidateRecord]) -> list[CandidateRecord]:
"""Score and rank candidates. Returns sorted list with ranks assigned."""
for candidate in candidates:
headroom = max(0.0, min(candidate.predicted_headroom_gb, 2.0))
headroom_score = headroom / 2.0 # 0-1, plateaus at 2 GB
arch_score = {"GQA": 1.0, "MHA": 0.7, "MQA": 0.5}.get(candidate.arch_type, 0.5)
tokenizer_score = candidate.tokenizer_compat_score # already 0-1
published_score = 0.15 if candidate.has_published_sensitivity_profile else 0.0
# Weighted composite
candidate.composite_score = (
0.30 * headroom_score + 0.25 * arch_score + 0.30 * tokenizer_score + 0.15 * published_score
)
# Sort descending by composite score
candidates.sort(key=lambda c: c.composite_score, reverse=True)
# Assign ranks
for i, candidate in enumerate(candidates):
candidate.rank = i + 1
if candidates:
logger.info(
"Score: top candidate %s (%.3f), %d ranked",
candidates[0].model_id,
candidates[0].composite_score,
len(candidates),
)
return candidates
# ── Emit Stage ─────────────────────────────────────────────────────────────
class EmitStage:
"""Stage 5: Final eligibility classification (green / yellow / red)."""
def emit(self, candidates: list[CandidateRecord]) -> list[CandidateRecord]:
"""Classify each candidate and attach eligibility reasons."""
for candidate in candidates:
reasons: list[str] = []
score = 0 # greenness score: higher is better
# Headroom
if candidate.predicted_headroom_gb >= 1.0:
score += 3
reasons.append(f"comfortable headroom ({candidate.predicted_headroom_gb:.1f} GB)")
elif candidate.predicted_headroom_gb >= 0.0:
score += 1
reasons.append(f"tight headroom ({candidate.predicted_headroom_gb:.1f} GB)")
else:
score -= 1
reasons.append(f"negative headroom ({candidate.predicted_headroom_gb:.1f} GB)")
# Arch
if candidate.arch_type == "GQA":
score += 2
reasons.append("GQA (cheaper KV cache)")
elif candidate.arch_type == "MHA":
score += 1
reasons.append("MHA (pruning-eligible)")
# Profile
if candidate.has_published_sensitivity_profile:
score += 1
reasons.append("published sensitivity profile available")
# Tokenizer
if candidate.tokenizer_compat_score >= 0.85:
score += 1
reasons.append(f"tokenizer compat {candidate.tokenizer_compat_score:.2f}")
# Pruning
if candidate.pruning_eligible:
reasons.append("pruning-eligible (MHA)")
# Determine eligibility
if score >= 4:
candidate.hsaq_eligibility = "green"
elif score >= 2:
candidate.hsaq_eligibility = "yellow"
else:
candidate.hsaq_eligibility = "red"
candidate.eligibility_reasons = reasons
green = sum(1 for c in candidates if c.hsaq_eligibility == "green")
yellow = sum(1 for c in candidates if c.hsaq_eligibility == "yellow")
red = sum(1 for c in candidates if c.hsaq_eligibility == "red")
logger.info("Emit: %d green, %d yellow, %d red", green, yellow, red)
return candidates
# ── Model Hunter Pipeline ──────────────────────────────────────────────────
@dataclass
class HunterConfig:
"""Configuration for the full model hunter pipeline."""
hf_queries: list[str] = field(
default_factory=lambda: [
"llama-3",
"qwen2.5",
"mistral",
"deepseek-coder",
"phi-3",
"gemma-2",
]
)
hf_limit_per_query: int = 10
hf_token: str | None = None
top_n_for_profiling: int = 5
filter_config: FilterConfig = field(default_factory=FilterConfig)
output_dir: str = "/mnt/Master_Chief/hsaq_hunter"
run_profiling: bool = False # Stage 4 requires GPU; skip for dry runs
class ModelHunterPipeline:
"""5-stage model hunter pipeline.
Stages 1-3 and 5 are pure computation (no GPU needed).
Stage 4 (profiling) is VRAM-heavy and requires the inference queue.
Usage:
hunter = ModelHunterPipeline(HunterConfig())
results = hunter.run() # returns list[CandidateRecord] sorted by rank
"""
def __init__(self, config: HunterConfig):
self.config = config
self.discovery = DiscoveryStage()
self.filter_stage = FilterStage(config.filter_config)
self.score_stage = ScoreStage()
self.emit_stage = EmitStage()
def run(self) -> list[CandidateRecord]:
"""Execute the full 5-stage hunter pipeline."""
start = time.time()
logger.info("=" * 60)
logger.info("HSAQ Model Hunter β€” Pipeline v%s", PIPELINE_VERSION)
logger.info("=" * 60)
# ── Stage 1: Discovery ─────────────────────────────────────────
logger.info("[Stage 1/5] DISCOVERY β€” searching HF Hub...")
candidates = self.discovery.discover_from_hf(
self.config.hf_queries,
limit_per_query=self.config.hf_limit_per_query,
hf_token=self.config.hf_token,
)
if not candidates:
logger.warning("Discovery returned 0 candidates. Check queries or HF connectivity.")
return []
# ── Stage 2: Filter ────────────────────────────────────────────
logger.info("[Stage 2/5] FILTER β€” killing non-viable candidates...")
survivors = self.filter_stage.filter(candidates)
if not survivors:
logger.warning("All candidates filtered out. Relax filter constraints.")
return []
# ── Stage 3: Score ────────────────────────────────────────────
logger.info("[Stage 3/5] SCORE β€” ranking %d survivors...", len(survivors))
ranked = self.score_stage.score(survivors)
# ── Stage 4: Profile ───────────────────────────────────────────
top_n = ranked[: self.config.top_n_for_profiling]
logger.info("[Stage 4/5] PROFILE β€” top %d candidates", len(top_n))
if self.config.run_profiling:
for candidate in top_n:
if candidate.has_published_sensitivity_profile:
logger.info(
" Skipping %s: published profile available (%s)",
candidate.model_id,
candidate.published_profile_source,
)
continue
logger.info(" Profiling %s (rank #%d)...", candidate.model_id, candidate.rank)
self._profile_candidate(candidate)
else:
logger.info(" Profiling SKIPPED (run_profiling=False, dry-run mode)")
# ── Stage 5: Emit ──────────────────────────────────────────────
logger.info("[Stage 5/5] EMIT β€” final eligibility classification...")
final = self.emit_stage.emit(top_n)
# Save results
self._save_results(final)
elapsed = time.time() - start
logger.info("Hunter complete in %.1f seconds", elapsed)
self._print_summary(final)
return final
def _profile_candidate(self, candidate: CandidateRecord) -> None:
"""Run HSAQ sensitivity profiling on a candidate (Stage 4).
This is VRAM-heavy. In production, this escalates through the
inference queue gateway and PermissionGate.
"""
try:
from quantization.hsaq.pipeline import HSAQPipeline
hsaq_config = HSAQConfig(
model_id=candidate.model_id,
output_dir=f"{self.config.output_dir}/profiles",
)
pipeline = HSAQPipeline(hsaq_config)
pipeline.run()
candidate.has_published_sensitivity_profile = True
candidate.published_profile_source = "hsaq-hunter-local"
except Exception as exc:
logger.error("Profiling failed for %s: %s", candidate.model_id, exc)
def _save_results(self, candidates: list[CandidateRecord]) -> None:
"""Persist hunter results to disk."""
output_path = Path(self.config.output_dir)
output_path.mkdir(parents=True, exist_ok=True)
results = {
"pipeline_version": PIPELINE_VERSION,
"timestamp": datetime.now(UTC).isoformat(),
"candidates": [
{
"model_id": c.model_id,
"model_hash": c.model_hash,
"arch_type": c.arch_type,
"param_count": c.param_count,
"num_kv_heads": c.num_kv_heads,
"head_dim": c.head_dim,
"num_layers": c.num_layers,
"tokenizer_family": c.tokenizer_family,
"tokenizer_compat_score": c.tokenizer_compat_score,
"predicted_vram_total_4k": c.predicted_vram_total_4k,
"predicted_headroom_gb": c.predicted_headroom_gb,
"hsaq_eligibility": c.hsaq_eligibility,
"eligibility_reasons": c.eligibility_reasons,
"composite_score": c.composite_score,
"rank": c.rank,
"pruning_eligible": c.pruning_eligible,
"has_published_sensitivity_profile": c.has_published_sensitivity_profile,
"license": c.license,
}
for c in candidates
],
}
(output_path / "hunter_results.json").write_text(json.dumps(results, indent=2))
logger.info("Hunter results saved to %s", output_path / "hunter_results.json")
def _print_summary(self, candidates: list[CandidateRecord]) -> None:
"""Print a human-readable summary table."""
print("\n" + "=" * 90)
print("HSAQ MODEL HUNTER β€” RESULTS")
print("=" * 90)
print(f"{'Rank':<5} {'Model':<40} {'Params':<10} {'VRAM':<8} {'Headroom':<10} {'Elig':<8} {'Score':<7}")
print("-" * 90)
for c in candidates[:15]:
print(
f"{c.rank:<5} {c.model_id[:38]:<40} "
f"{_fmt_params(c.param_count):<10} "
f"{c.predicted_vram_total_4k:.1f} GB{'':<3} "
f"{c.predicted_headroom_gb:.1f} GB{'':<3} "
f"{c.hsaq_eligibility:<8} "
f"{c.composite_score:.3f}"
)
print("=" * 90)
def _fmt_params(n: int) -> str:
"""Format parameter count in B/M notation."""
if n >= 1_000_000_000:
return f"{n / 1_000_000_000:.1f}B"
if n >= 1_000_000:
return f"{n / 1_000_000:.0f}M"
return str(n)