""" HSAQ Layer Sensitivity Profiler — v1.1.0 ========================================= Measures per-layer output drift under different quantization levels by running real calibration data through the model and comparing each quantized layer's output to its fp16 baseline on the SAME input. What changed in v1.1.0 (PIPELINE_VERSION bumped): - Drift is now measured on captured calibration activations, not random Gaussian inputs. Previous cached profiles are noise-derived and must be invalidated (PIPELINE_VERSION bump triggers this automatically). - _capture_baseline now captures (input, output) pairs per layer, not just outputs. The captured input is what we actually need to re-run each layer under simulated quantization. - Drift is averaged across n samples for stability, instead of being measured once on the first sample only. - param_count is now populated in cache rows (was 0, which broke the budget calculator on cache hits). Algorithm: 1. Load model in fp16/bf16 on the inference device. 2. For each calibration sample S of n: a. Forward pass with hooks that capture (input, output) per Linear layer. b. For each layer x each bit-width in {2,3,4}: - Temporarily swap in a simulated-quantized weight. - Re-run that layer's forward on the captured input. - Compute normalized MSE vs the captured baseline output. - Accumulate drift. c. Free the sample's captured activations before processing the next. 3. After all samples, divide by n to get mean drift per (layer, nbits). Memory: peak ~1x sample worth of layer I/O held in CPU at a time, not nx. """ from __future__ import annotations import hashlib import json import logging import sqlite3 import time from datetime import UTC, datetime from pathlib import Path import torch import torch.nn as nn from tqdm import tqdm from quantization.hsaq.config import ( HSAQConfig, LayerSensitivity, SensitivityResult, ) logger = logging.getLogger("HSAQ.Sensitivity") # Bumped from 1.0.0 — drift metric changed from "MSE on random input" to # "normalized MSE on captured calibration input". Cached rows under 1.0.0 # are noise-derived and must not be reused. PIPELINE_VERSION = "1.1.0" # ── SQLite Sensitivity Cache ─────────────────────────────────────────────── SCHEMA_DDL = """ CREATE TABLE IF NOT EXISTS sensitivity_profile ( model_hash TEXT NOT NULL, calibration_hash TEXT NOT NULL, layer_idx INTEGER NOT NULL, component TEXT NOT NULL, layer_name TEXT NOT NULL, layer_type TEXT NOT NULL, param_count INTEGER NOT NULL DEFAULT 0, drift_2bit REAL, drift_3bit REAL, drift_4bit REAL, assigned_tier TEXT NOT NULL, assigned_bits INTEGER NOT NULL, quantizer_choice TEXT NOT NULL, profiled_at TEXT NOT NULL, pipeline_version TEXT NOT NULL, PRIMARY KEY (model_hash, calibration_hash, layer_idx, component, pipeline_version) ); CREATE INDEX IF NOT EXISTS idx_profile_lookup ON sensitivity_profile(model_hash, calibration_hash, pipeline_version); """ class SensitivityCacheDB: """SQLite-backed sensitivity profile cache. NOTE: This is a local-only cache that does not route through the Vault module. In the integrated Sovereign Hive deployment, this should be replaced with calls into the Vault module (see the migration_002 table). Kept as-is here to minimize blast radius of the drift-measurement fix. """ def __init__(self, db_path: str | Path): self.db_path = Path(db_path) self.db_path.parent.mkdir(parents=True, exist_ok=True) self._init_db() def _init_db(self) -> None: with sqlite3.connect(str(self.db_path)) as conn: conn.executescript(SCHEMA_DDL) conn.commit() def has_profile( self, model_hash: str, calibration_hash: str, pipeline_version: str = PIPELINE_VERSION, ) -> bool: with sqlite3.connect(str(self.db_path)) as conn: row = conn.execute( "SELECT 1 FROM sensitivity_profile " "WHERE model_hash = ? AND calibration_hash = ? AND pipeline_version = ? " "LIMIT 1", (model_hash, calibration_hash, pipeline_version), ).fetchone() return row is not None def load( self, model_hash: str, calibration_hash: str, pipeline_version: str = PIPELINE_VERSION, ) -> SensitivityResult | None: with sqlite3.connect(str(self.db_path)) as conn: rows = conn.execute( "SELECT layer_idx, component, layer_name, layer_type, param_count, " "drift_2bit, drift_3bit, drift_4bit, assigned_tier, assigned_bits, " "quantizer_choice " "FROM sensitivity_profile " "WHERE model_hash = ? AND calibration_hash = ? AND pipeline_version = ? " "ORDER BY layer_idx", (model_hash, calibration_hash, pipeline_version), ).fetchall() if not rows: return None layers: list[LayerSensitivity] = [] for row in rows: (_idx, _component, layer_name, layer_type, param_count, d2, d3, d4, _tier, _bits, _quant) = row layers.append( LayerSensitivity( layer_name=layer_name, layer_type=layer_type, output_drift_2bit=d2 or 0.0, output_drift_3bit=d3 or 0.0, output_drift_4bit=d4 or 0.0, param_count=param_count, # now populated weight_size_fp16_gb=param_count * 2 / 1e9, # derive on load ) ) return SensitivityResult( model_id=model_hash, model_param_count=sum(ly.param_count for ly in layers), model_size_fp16_gb=sum(ly.weight_size_fp16_gb for ly in layers), layers=layers, calibration_dataset=calibration_hash, calibration_samples=0, ) def save( self, model_hash: str, calibration_hash: str, result: SensitivityResult, quantizer_choice: str = "hqq", pipeline_version: str = PIPELINE_VERSION, ) -> None: now = datetime.now(UTC).isoformat() with sqlite3.connect(str(self.db_path)) as conn: for idx, layer in enumerate(result.layers): conn.execute( "INSERT OR REPLACE INTO sensitivity_profile " "(model_hash, calibration_hash, layer_idx, component, " "layer_name, layer_type, param_count, " "drift_2bit, drift_3bit, drift_4bit, assigned_tier, " "assigned_bits, quantizer_choice, profiled_at, pipeline_version) " "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ( model_hash, calibration_hash, idx, layer.layer_type, layer.layer_name, layer.layer_type, layer.param_count, layer.output_drift_2bit, layer.output_drift_3bit, layer.output_drift_4bit, layer.assigned_tier.value, layer.recommended_nbits, quantizer_choice, now, pipeline_version, ), ) conn.commit() logger.info("Saved %d layers to cache (%s)", len(result.layers), self.db_path) # ── Profiler ─────────────────────────────────────────────────────────────── class SensitivityProfiler: """Profiles per-layer sensitivity to quantization by measuring output drift on real calibration data.""" def __init__(self, config: HSAQConfig): self.config = config self._calibration_cache: Path | None = None if config.save_calibration_cache: cache_dir = Path(config.output_dir) / ".hsaq_cache" cache_dir.mkdir(parents=True, exist_ok=True) model_slug = config.model_id.replace("/", "__") self._calibration_cache = cache_dir / f"{model_slug}_sensitivity.json" self._sqlite_cache = SensitivityCacheDB(cache_dir / "sensitivity_profiles.db") # ── Public API ─────────────────────────────────────────────────────── def profile(self, model: nn.Module) -> SensitivityResult: """Run full sensitivity profiling on a model.""" model_hash = self._compute_model_hash(model) calib_hash = self._compute_calibration_hash() # Cache lookup if ( self.config.save_calibration_cache and hasattr(self, "_sqlite_cache") and self._sqlite_cache.has_profile(model_hash, calib_hash) ): logger.info("Cache hit (model=%s, calib=%s)", model_hash[:8], calib_hash[:8]) cached = self._sqlite_cache.load(model_hash, calib_hash) if cached is not None: cached.model_id = self.config.model_id cached.calibration_dataset = self.config.calibration_dataset cached.calibration_samples = self.config.calibration_samples return cached logger.info("Profiling layer sensitivity for %s", self.config.model_id) start = time.time() # 1. Gather quantizable layers quantizable_layers = self._find_quantizable_layers(model) logger.info("Found %d quantizable layers", len(quantizable_layers)) # 2. Load calibration data calib_inputs = self._load_calibration_data() n_samples = min(len(calib_inputs), self.config.calibration_samples) logger.info("Using %d calibration samples", n_samples) # 3. Pre-compute quantized weights once per layer per nbits (cheap). # Stays on CPU; moved to layer device per drift measurement. quantized_weights: dict[str, dict[int, torch.Tensor]] = {} for name, layer in quantizable_layers: quantized_weights[name] = { nbits: self._simulate_quantize(layer.weight.data.detach().cpu(), nbits) for nbits in [2, 3, 4] # always compute all 3 for the result row } # 4. Accumulators drift_accum: dict[str, dict[int, float]] = {name: {2: 0.0, 3: 0.0, 4: 0.0} for name, _ in quantizable_layers} drift_count: dict[str, int] = {name: 0 for name, _ in quantizable_layers} # 5. Per-sample loop — capture I/O on real data, compute drift, free. for sample_idx in tqdm(range(n_samples), desc="Profiling drift"): sample = calib_inputs[sample_idx] layer_io = self._capture_layer_io(model, quantizable_layers, sample) for name, layer in quantizable_layers: if name not in layer_io: continue inp_cpu, base_out_cpu = layer_io[name] for nbits in [2, 3, 4]: qw_cpu = quantized_weights[name][nbits] drift = self._drift_from_captured(layer, inp_cpu, base_out_cpu, qw_cpu) drift_accum[name][nbits] += drift drift_count[name] += 1 layer_io.clear() # 6. Build LayerSensitivity entries with averaged drift layers: list[LayerSensitivity] = [] for name, layer in quantizable_layers: n = max(drift_count[name], 1) ds = drift_accum[name] layers.append( LayerSensitivity( layer_name=name, layer_type=self._classify_layer_type(name), output_drift_2bit=ds[2] / n, output_drift_3bit=ds[3] / n, output_drift_4bit=ds[4] / n, param_count=layer.weight.numel(), weight_size_fp16_gb=layer.weight.numel() * 2 / 1e9, ) ) total_params = sum(p.numel() for p in model.parameters()) result = SensitivityResult( model_id=self.config.model_id, model_param_count=total_params, model_size_fp16_gb=total_params * 2 / 1e9, layers=layers, calibration_dataset=self.config.calibration_dataset, calibration_samples=n_samples, ) elapsed = time.time() - start logger.info( "Sensitivity profiling complete in %.1fs — %d layers, tier dist: %s", elapsed, len(layers), {k: f"{v:.1%}" for k, v in result.tier_distribution.items()}, ) # 7. Persist if self._calibration_cache: self._save_cache(result) if self.config.save_calibration_cache and hasattr(self, "_sqlite_cache"): self._sqlite_cache.save( model_hash, calib_hash, result, quantizer_choice=self.config.quantizer_backend_3bit, ) return result # ── Layer discovery ────────────────────────────────────────────────── def _find_quantizable_layers(self, model: nn.Module) -> list[tuple[str, nn.Module]]: layers: list[tuple[str, nn.Module]] = [] for name, module in model.named_modules(): if isinstance(module, nn.Linear): if module.weight.numel() < 4096: continue layers.append((name, module)) return layers # ── Calibration data loading ───────────────────────────────────────── def _load_calibration_data(self) -> list[dict[str, torch.Tensor]]: """Load calibration samples, or fall back to random tokens. NOTE: The fallback to random tokens still produces semi-realistic sequences (not pure Gaussian noise on activations). The drift measurement now propagates real model state through the network, so even random tokens give signal that's tied to weight statistics on whatever the embedding produces. Real text is still preferred. """ from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained( self.config.model_id, cache_dir=self.config.cache_dir, token=self.config.hf_token, ) if tokenizer.pad_token is None: tokenizer.pad_token = tokenizer.eos_token samples: list[dict[str, torch.Tensor]] = [] try: from datasets import load_dataset dataset = load_dataset( self.config.calibration_dataset, "wikitext-2-raw-v1", split="train", trust_remote_code=True, ) texts = dataset["text"][: self.config.calibration_samples * 2] texts = [t for t in texts if len(t.strip()) > 50][: self.config.calibration_samples] for text in texts: enc = tokenizer( text, return_tensors="pt", truncation=True, max_length=self.config.calibration_max_length, ) samples.append(enc) return samples except Exception: logger.warning( "Could not load %s — falling back to random token sequences", self.config.calibration_dataset, ) vocab_size = tokenizer.vocab_size for _ in range(self.config.calibration_samples): seq_len = min(self.config.calibration_max_length, 512) tokens = torch.randint(0, vocab_size, (1, seq_len)) samples.append( { "input_ids": tokens, "attention_mask": torch.ones_like(tokens), } ) return samples # ── Per-sample I/O capture ─────────────────────────────────────────── def _capture_layer_io( self, model: nn.Module, quantizable_layers: list[tuple[str, nn.Module]], sample: dict[str, torch.Tensor], ) -> dict[str, tuple[torch.Tensor, torch.Tensor]]: """Run a single forward pass with hooks that capture (input, output) per Linear layer. Captured tensors are moved to CPU to bound GPU memory. """ layer_io: dict[str, tuple[torch.Tensor, torch.Tensor]] = {} hooks: list = [] def make_hook(name: str): def hook(_module, inputs, output): if not inputs: return inp = inputs[0] if not isinstance(inp, torch.Tensor): return if isinstance(output, torch.Tensor): out = output elif isinstance(output, (tuple, list)) and isinstance(output[0], torch.Tensor): out = output[0] else: return # Move captured tensors to CPU to keep GPU memory bounded. layer_io[name] = (inp.detach().to("cpu"), out.detach().to("cpu")) return hook for name, module in quantizable_layers: hooks.append(module.register_forward_hook(make_hook(name))) try: device = next(model.parameters()).device sample_dev = {k: v.to(device) if torch.is_tensor(v) else v for k, v in sample.items()} model.eval() with torch.no_grad(): try: model(**sample_dev) except TypeError: if "input_ids" in sample_dev: model(sample_dev["input_ids"]) else: raise finally: for h in hooks: h.remove() return layer_io # ── Drift measurement (the fix) ────────────────────────────────────── def _drift_from_captured( self, layer: nn.Linear, inp_cpu: torch.Tensor, baseline_out_cpu: torch.Tensor, quantized_weight_cpu: torch.Tensor, ) -> float: """Normalized MSE between baseline output and quantized output on the same captured input. Both tensors live on CPU at entry; we move only what's needed onto the layer's device for the brief forward.""" device = layer.weight.device dtype = layer.weight.dtype inp = inp_cpu.to(device=device, dtype=dtype) baseline = baseline_out_cpu.to(device=device, dtype=dtype) qw = quantized_weight_cpu.to(device=device, dtype=dtype) orig_weight = layer.weight.data try: layer.weight.data = qw with torch.no_grad(): quant_out = layer(inp) finally: layer.weight.data = orig_weight # Normalized MSE — invariant to layer output scale. mse = ((quant_out - baseline) ** 2).mean().item() norm = (baseline**2).mean().item() return mse / max(norm, 1e-8) def _simulate_quantize(self, weight: torch.Tensor, nbits: int) -> torch.Tensor: """Per-tensor symmetric uniform quantization (fast approximation of HQQ). For sensitivity *ranking*, relative drift across layers is what matters; absolute drift values are not directly comparable to a real HQQ deployment. For exact HQQ-matched drift, call HQQ's own quantize. """ if nbits >= 8: return weight w_min, w_max = weight.min(), weight.max() scale = (w_max - w_min) / (2**nbits - 1) if scale == 0: return weight return torch.round((weight - w_min) / scale) * scale + w_min # ── Layer classification ───────────────────────────────────────────── def _classify_layer_type(self, name: str) -> str: name_lower = name.lower() if "embed" in name_lower: return "embedding" if "lm_head" in name_lower or "output" in name_lower: return "lm_head" if any(k in name_lower for k in ("q_proj", "k_proj", "v_proj", "o_proj", "attention", "attn")): return "attention" if any(k in name_lower for k in ("gate_proj", "up_proj", "down_proj", "mlp", "ffn", "feed_forward")): return "mlp" if "norm" in name_lower: return "norm" return "linear" # ── Cache hashing ──────────────────────────────────────────────────── def _compute_model_hash(self, model: nn.Module) -> str: parts: list[str] = [] for name, param in model.named_parameters(): parts.append(f"{name}:{list(param.shape)}") payload = json.dumps(sorted(parts)) return hashlib.sha256(payload.encode()).hexdigest()[:16] def _compute_calibration_hash(self) -> str: payload = json.dumps( { "dataset": self.config.calibration_dataset, "samples": self.config.calibration_samples, "max_length": self.config.calibration_max_length, }, sort_keys=True, ) return hashlib.sha256(payload.encode()).hexdigest()[:16] # ── JSON cache (legacy, kept for compatibility) ────────────────────── def _save_cache(self, result: SensitivityResult) -> None: if not self._calibration_cache: return data = { "model_id": result.model_id, "model_param_count": result.model_param_count, "model_size_fp16_gb": result.model_size_fp16_gb, "calibration_dataset": result.calibration_dataset, "calibration_samples": result.calibration_samples, "pipeline_version": PIPELINE_VERSION, "layers": [ { "layer_name": layer.layer_name, "layer_type": layer.layer_type, "output_drift_2bit": layer.output_drift_2bit, "output_drift_3bit": layer.output_drift_3bit, "output_drift_4bit": layer.output_drift_4bit, "param_count": layer.param_count, "weight_size_fp16_gb": layer.weight_size_fp16_gb, } for layer in result.layers ], } self._calibration_cache.write_text(json.dumps(data, indent=2)) logger.info("Saved sensitivity cache to %s", self._calibration_cache)