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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Sovereign Hive HSAQ β KV-cache sensitivity profiler
|
| 3 |
+
====================================================
|
| 4 |
+
|
| 5 |
+
Sweeps each attention layer across a curated 11-config grid of
|
| 6 |
+
(k_bits, v_bits, quantizer) combinations and measures the resulting
|
| 7 |
+
attention-output drift on calibration data. Emits ProfileRow objects
|
| 8 |
+
ready for insertion into the `kv_sensitivity_profile` Vault table
|
| 9 |
+
(migration 003).
|
| 10 |
+
|
| 11 |
+
Why this file exists:
|
| 12 |
+
The KV cache is the bigger lever than weight quantization for MHA
|
| 13 |
+
models on 12 GB cards (e.g. OLMo: ~3.3 GB KV at 4K ctx fp16, more than
|
| 14 |
+
the weights). The allocator needs measured drift values to pick which
|
| 15 |
+
layers can tolerate aggressive KV quant. This profiler is what feeds it.
|
| 16 |
+
|
| 17 |
+
Pure-logic conventions (matching candidate_record.py):
|
| 18 |
+
- No Vault writes. Caller persists the emitted ProfileRows.
|
| 19 |
+
- No PermissionGate routing here. Caller (the hunter agent) handles that.
|
| 20 |
+
- All disk/network I/O is the caller's job. We accept a loaded model
|
| 21 |
+
and tokenizer; we return data structures.
|
| 22 |
+
|
| 23 |
+
What this DOES touch:
|
| 24 |
+
- GPU forward passes (calls `model(**batch)` under torch.no_grad).
|
| 25 |
+
- kv_intercept.kv_quant_active context manager to install hooks.
|
| 26 |
+
- Hook lifecycle (always cleaned up via context manager β verified in
|
| 27 |
+
smoke_test_v3.py test #6).
|
| 28 |
+
|
| 29 |
+
What this does NOT do:
|
| 30 |
+
- It does not handle inference-queue gating. If two profilers run
|
| 31 |
+
concurrently on the same GPU, you'll OOM. Caller must serialize.
|
| 32 |
+
- It does not write to disk. Output is in-memory ProfileRow objects.
|
| 33 |
+
- It does not bump pipeline_version. The constant lives here as a
|
| 34 |
+
reference value; callers wanting a different lineage pass their own.
|
| 35 |
+
|
| 36 |
+
Config sweep rationale (11 per layer):
|
| 37 |
+
Full Cartesian (5 k_bits Γ 5 v_bits Γ 4 quantizers) = 100/layer is way
|
| 38 |
+
overkill β most combinations carry no signal the allocator can use.
|
| 39 |
+
This curated 11 covers the decision boundaries that actually matter:
|
| 40 |
+
|
| 41 |
+
Symmetric K=V (the common case): (8,8), (4,4), (3,3), (2,2) hqq_g64
|
| 42 |
+
K-cheaper-than-V (K more tolerant): (4,8), (3,8), (2,8), (2,4) hqq_g64
|
| 43 |
+
Quantizer comparison: (4,4) scaled_uniform
|
| 44 |
+
(4,4) scaled_per_head
|
| 45 |
+
(8,8) scaled_uniform
|
| 46 |
+
|
| 47 |
+
For OLMo (40 layers): 11 Γ 40 = 440 forward passes. On consumer GPU at
|
| 48 |
+
~2-3 s/pass that's ~15-20 min for the full sweep. Caching by
|
| 49 |
+
(model_hash, calibration_hash, pipeline_version) means you pay this
|
| 50 |
+
once per model+calibration pair, not every run.
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
from __future__ import annotations
|
| 54 |
+
|
| 55 |
+
import hashlib
|
| 56 |
+
import json
|
| 57 |
+
import logging
|
| 58 |
+
import time
|
| 59 |
+
from dataclasses import dataclass, field
|
| 60 |
+
from datetime import UTC, datetime
|
| 61 |
+
from typing import Callable, Iterable, Literal, Optional
|
| 62 |
+
|
| 63 |
+
logger = logging.getLogger("HSAQ.KVProfiler")
|
| 64 |
+
|
| 65 |
+
# Bump when changing the config sweep, drift metric implementation, or
|
| 66 |
+
# hook semantics. Cached rows under earlier versions become lookup-misses
|
| 67 |
+
# so they're safely ignored rather than silently reused.
|
| 68 |
+
PIPELINE_VERSION = "1.0.0"
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
# ---------------------------------------------------------------------------
|
| 72 |
+
# Types
|
| 73 |
+
# ---------------------------------------------------------------------------
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
DriftMetric = Literal["mse_normalised", "kl_softmax"]
|
| 77 |
+
KVQuantizer = Literal["hqq_g64", "scaled_uniform", "scaled_per_head", "fp16_passthrough"]
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
@dataclass(frozen=True)
|
| 81 |
+
class SweepConfig:
|
| 82 |
+
"""One (k_bits, v_bits, quantizer) probe to measure on every layer."""
|
| 83 |
+
k_bits: int
|
| 84 |
+
v_bits: int
|
| 85 |
+
quantizer: KVQuantizer
|
| 86 |
+
group_size: int = 64
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
@dataclass
|
| 90 |
+
class ProfileRow:
|
| 91 |
+
"""One row of measured KV sensitivity. Shape matches the Vault table
|
| 92 |
+
kv_sensitivity_profile (migration 003) exactly β caller can insert
|
| 93 |
+
this dict directly or pass through a Vault adapter."""
|
| 94 |
+
model_hash: str
|
| 95 |
+
calibration_hash: str
|
| 96 |
+
pipeline_version: str
|
| 97 |
+
layer_idx: int
|
| 98 |
+
k_bits: int
|
| 99 |
+
v_bits: int
|
| 100 |
+
quantizer: str
|
| 101 |
+
drift_attn_output: float
|
| 102 |
+
drift_metric: str
|
| 103 |
+
bytes_per_kv_token: float
|
| 104 |
+
max_seq_len_observed: int
|
| 105 |
+
num_kv_heads: int
|
| 106 |
+
head_dim: int
|
| 107 |
+
profiled_at: str
|
| 108 |
+
profiled_by_agent_id: str
|
| 109 |
+
profiled_by_agent_tier: int
|
| 110 |
+
|
| 111 |
+
def to_vault_payload(self) -> dict:
|
| 112 |
+
"""Row-shaped dict ready for INSERT into kv_sensitivity_profile."""
|
| 113 |
+
return {
|
| 114 |
+
"model_hash": self.model_hash,
|
| 115 |
+
"calibration_hash": self.calibration_hash,
|
| 116 |
+
"pipeline_version": self.pipeline_version,
|
| 117 |
+
"layer_idx": self.layer_idx,
|
| 118 |
+
"k_bits": self.k_bits,
|
| 119 |
+
"v_bits": self.v_bits,
|
| 120 |
+
"quantizer": self.quantizer,
|
| 121 |
+
"drift_attn_output": self.drift_attn_output,
|
| 122 |
+
"drift_metric": self.drift_metric,
|
| 123 |
+
"bytes_per_kv_token": self.bytes_per_kv_token,
|
| 124 |
+
"max_seq_len_observed": self.max_seq_len_observed,
|
| 125 |
+
"num_kv_heads": self.num_kv_heads,
|
| 126 |
+
"head_dim": self.head_dim,
|
| 127 |
+
"profiled_at": self.profiled_at,
|
| 128 |
+
"profiled_by_agent_id": self.profiled_by_agent_id,
|
| 129 |
+
"profiled_by_agent_tier": self.profiled_by_agent_tier,
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
# ---------------------------------------------------------------------------
|
| 134 |
+
# Default sweep β the curated 11 configs
|
| 135 |
+
# ---------------------------------------------------------------------------
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
DEFAULT_SWEEP: tuple[SweepConfig, ...] = (
|
| 139 |
+
# ββ Symmetric K=V (most common case, 4 configs) ββββββββββββββββββββββ
|
| 140 |
+
SweepConfig(k_bits=8, v_bits=8, quantizer="hqq_g64"),
|
| 141 |
+
SweepConfig(k_bits=4, v_bits=4, quantizer="hqq_g64"),
|
| 142 |
+
SweepConfig(k_bits=3, v_bits=3, quantizer="hqq_g64"),
|
| 143 |
+
SweepConfig(k_bits=2, v_bits=2, quantizer="hqq_g64"),
|
| 144 |
+
# ββ K-cheaper-than-V (K is more error-tolerant, 4 configs) βββββββββββ
|
| 145 |
+
SweepConfig(k_bits=4, v_bits=8, quantizer="hqq_g64"),
|
| 146 |
+
SweepConfig(k_bits=3, v_bits=8, quantizer="hqq_g64"),
|
| 147 |
+
SweepConfig(k_bits=2, v_bits=8, quantizer="hqq_g64"),
|
| 148 |
+
SweepConfig(k_bits=2, v_bits=4, quantizer="hqq_g64"),
|
| 149 |
+
# ββ Quantizer comparison (3 configs) ββββββββββββββββββββββββββββββββββ
|
| 150 |
+
SweepConfig(k_bits=4, v_bits=4, quantizer="scaled_uniform"),
|
| 151 |
+
SweepConfig(k_bits=4, v_bits=4, quantizer="scaled_per_head"),
|
| 152 |
+
SweepConfig(k_bits=8, v_bits=8, quantizer="scaled_uniform"),
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
# ---------------------------------------------------------------------------
|
| 157 |
+
# Bytes-per-KV-token accounting
|
| 158 |
+
# ---------------------------------------------------------------------------
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def kv_bytes_per_token(
|
| 162 |
+
num_kv_heads: int,
|
| 163 |
+
head_dim: int,
|
| 164 |
+
k_bits: int,
|
| 165 |
+
v_bits: int,
|
| 166 |
+
quantizer: KVQuantizer,
|
| 167 |
+
group_size: int = 64,
|
| 168 |
+
) -> float:
|
| 169 |
+
"""Bytes per token of KV cache for one layer at the given config.
|
| 170 |
+
|
| 171 |
+
Includes quantizer-specific overhead (scales / zeros). The allocator
|
| 172 |
+
reads this value cached in the Vault rather than recomputing, so the
|
| 173 |
+
formula here is the single source of truth β change it, bump
|
| 174 |
+
PIPELINE_VERSION.
|
| 175 |
+
"""
|
| 176 |
+
elems = num_kv_heads * head_dim
|
| 177 |
+
|
| 178 |
+
if quantizer == "fp16_passthrough":
|
| 179 |
+
# 2 bytes/elem Γ K and V both
|
| 180 |
+
return 2 * elems * 2 # K + V at fp16 (2 bytes/elem)
|
| 181 |
+
|
| 182 |
+
if quantizer == "scaled_uniform":
|
| 183 |
+
# One fp16 scale per row of K and V each
|
| 184 |
+
k_payload = elems * k_bits / 8
|
| 185 |
+
v_payload = elems * v_bits / 8
|
| 186 |
+
return (k_payload + 2) + (v_payload + 2)
|
| 187 |
+
|
| 188 |
+
if quantizer == "scaled_per_head":
|
| 189 |
+
# fp16 scale per head, per K/V
|
| 190 |
+
k_payload = elems * k_bits / 8
|
| 191 |
+
v_payload = elems * v_bits / 8
|
| 192 |
+
return (k_payload + num_kv_heads * 2) + (v_payload + num_kv_heads * 2)
|
| 193 |
+
|
| 194 |
+
if quantizer == "hqq_g64":
|
| 195 |
+
# Groups along the head_dim axis (per row of the KV cache).
|
| 196 |
+
# NOTE: this is the corrected accounting β earlier stub grouped
|
| 197 |
+
# along (num_kv_heads Γ head_dim) which underestimated overhead.
|
| 198 |
+
groups_per_row = max(1, head_dim // group_size)
|
| 199 |
+
# zero + scale per group, fp16 each = 4 bytes per group
|
| 200 |
+
overhead_per_row = num_kv_heads * groups_per_row * 4
|
| 201 |
+
k_payload = elems * k_bits / 8
|
| 202 |
+
v_payload = elems * v_bits / 8
|
| 203 |
+
return (k_payload + overhead_per_row) + (v_payload + overhead_per_row)
|
| 204 |
+
|
| 205 |
+
raise ValueError(f"unknown quantizer: {quantizer}")
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
# ---------------------------------------------------------------------------
|
| 209 |
+
# Drift metrics
|
| 210 |
+
# ---------------------------------------------------------------------------
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def compute_drift(quanted, baseline, metric: DriftMetric) -> float:
|
| 214 |
+
"""Compute attention-output drift between quanted and fp16 baseline.
|
| 215 |
+
|
| 216 |
+
mse_normalised: ((quanted - baseline)^2).mean() / baseline.abs().mean()^2
|
| 217 |
+
Scale-invariant. Recommended for allocator inputs. KIVI-style.
|
| 218 |
+
|
| 219 |
+
kl_softmax: KL divergence treating attention outputs as logits over the
|
| 220 |
+
last dim. PROVISIONAL β attention output isn't a distribution, so
|
| 221 |
+
this is a proxy metric only. Kept for compatibility with the
|
| 222 |
+
Vault schema; do NOT use as allocator input without validation.
|
| 223 |
+
"""
|
| 224 |
+
import torch
|
| 225 |
+
import torch.nn.functional as F
|
| 226 |
+
|
| 227 |
+
if metric == "mse_normalised":
|
| 228 |
+
mse = ((quanted - baseline) ** 2).mean().item()
|
| 229 |
+
denom = (baseline ** 2).mean().item()
|
| 230 |
+
return mse / max(denom, 1e-8)
|
| 231 |
+
|
| 232 |
+
if metric == "kl_softmax":
|
| 233 |
+
a = F.log_softmax(quanted.float().flatten(0, -2), dim=-1)
|
| 234 |
+
b = F.softmax(baseline.float().flatten(0, -2), dim=-1)
|
| 235 |
+
return float(F.kl_div(a, b, reduction="batchmean"))
|
| 236 |
+
|
| 237 |
+
raise ValueError(f"unknown drift metric: {metric}")
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
# ---------------------------------------------------------------------------
|
| 241 |
+
# Calibration hash
|
| 242 |
+
# ---------------------------------------------------------------------------
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def compute_calibration_hash(
|
| 246 |
+
calibration_texts: list[str],
|
| 247 |
+
max_seq_len: int,
|
| 248 |
+
) -> str:
|
| 249 |
+
"""Deterministic hash of calibration inputs for cache invalidation."""
|
| 250 |
+
payload = json.dumps({
|
| 251 |
+
"n_texts": len(calibration_texts),
|
| 252 |
+
"max_seq_len": max_seq_len,
|
| 253 |
+
# First/last text content matters for distinguishing calibration sets;
|
| 254 |
+
# hash a sample rather than every text to keep this cheap.
|
| 255 |
+
"first_text": calibration_texts[0][:200] if calibration_texts else "",
|
| 256 |
+
"last_text": calibration_texts[-1][:200] if calibration_texts else "",
|
| 257 |
+
"total_chars": sum(len(t) for t in calibration_texts),
|
| 258 |
+
}, sort_keys=True)
|
| 259 |
+
return hashlib.sha256(payload.encode()).hexdigest()[:16]
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
# ---------------------------------------------------------------------------
|
| 263 |
+
# Per-layer attention-output capture
|
| 264 |
+
# ---------------------------------------------------------------------------
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def _capture_attn_outputs(
|
| 268 |
+
model,
|
| 269 |
+
attn_modules_by_layer: dict[int, object],
|
| 270 |
+
batch,
|
| 271 |
+
) -> dict[int, "torch.Tensor"]:
|
| 272 |
+
"""Run one forward pass with hooks that capture attention output per layer.
|
| 273 |
+
|
| 274 |
+
HF attention modules return either `attn_output` directly or a tuple
|
| 275 |
+
starting with `attn_output`. We grab the first tensor element in either
|
| 276 |
+
case.
|
| 277 |
+
"""
|
| 278 |
+
import torch
|
| 279 |
+
|
| 280 |
+
captured: dict[int, torch.Tensor] = {}
|
| 281 |
+
handles: list = []
|
| 282 |
+
|
| 283 |
+
def make_hook(li: int):
|
| 284 |
+
def hook(_mod, _inp, out):
|
| 285 |
+
t = out[0] if isinstance(out, tuple) else out
|
| 286 |
+
if isinstance(t, torch.Tensor):
|
| 287 |
+
# Move to CPU to bound GPU memory across all captured layers
|
| 288 |
+
captured[li] = t.detach().to("cpu")
|
| 289 |
+
return hook
|
| 290 |
+
|
| 291 |
+
try:
|
| 292 |
+
for li, attn in attn_modules_by_layer.items():
|
| 293 |
+
handles.append(attn.register_forward_hook(make_hook(li)))
|
| 294 |
+
with torch.no_grad():
|
| 295 |
+
model(**batch, use_cache=False)
|
| 296 |
+
finally:
|
| 297 |
+
for h in handles:
|
| 298 |
+
h.remove()
|
| 299 |
+
|
| 300 |
+
return captured
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
# ---------------------------------------------------------------------------
|
| 304 |
+
# Profiler
|
| 305 |
+
# ---------------------------------------------------------------------------
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def profile_kv_sensitivity(
|
| 309 |
+
model,
|
| 310 |
+
tokenizer,
|
| 311 |
+
calibration_texts: list[str],
|
| 312 |
+
*,
|
| 313 |
+
model_hash: str,
|
| 314 |
+
profiled_by_agent_id: str,
|
| 315 |
+
profiled_by_agent_tier: int,
|
| 316 |
+
sweep: Iterable[SweepConfig] = DEFAULT_SWEEP,
|
| 317 |
+
drift_metric: DriftMetric = "mse_normalised",
|
| 318 |
+
max_seq_len: int = 1024,
|
| 319 |
+
pipeline_version: str = PIPELINE_VERSION,
|
| 320 |
+
progress_cb: Optional[Callable[[str], None]] = None,
|
| 321 |
+
) -> list[ProfileRow]:
|
| 322 |
+
"""Measure attention-output drift per (layer Γ sweep config).
|
| 323 |
+
|
| 324 |
+
Args:
|
| 325 |
+
model: HF model in eval mode on its target device.
|
| 326 |
+
tokenizer: Matching HF tokenizer.
|
| 327 |
+
calibration_texts: List of natural-language strings to feed through
|
| 328 |
+
the model. Length controls statistical robustness; quality of
|
| 329 |
+
the distribution match controls allocator decisions on out-of-
|
| 330 |
+
distribution data. 32-256 samples is the sweet spot.
|
| 331 |
+
model_hash: Deterministic identifier of the model (caller-computed).
|
| 332 |
+
Used as the first part of the cache invalidation key.
|
| 333 |
+
profiled_by_agent_id, profiled_by_agent_tier: Audit chain. Caller
|
| 334 |
+
is whatever agent invoked the profile (e.g. hunter at tier 2).
|
| 335 |
+
sweep: Iterable of SweepConfigs to measure. Defaults to the curated
|
| 336 |
+
11-config sweep documented in the module header.
|
| 337 |
+
drift_metric: "mse_normalised" (recommended) or "kl_softmax"
|
| 338 |
+
(provisional β see compute_drift docstring).
|
| 339 |
+
max_seq_len: Tokenizer truncation length and the max_seq_len_observed
|
| 340 |
+
column for emitted rows.
|
| 341 |
+
pipeline_version: Override only when running a deliberately
|
| 342 |
+
distinct lineage (e.g. comparing two metric implementations).
|
| 343 |
+
progress_cb: Optional callback for progress messages.
|
| 344 |
+
|
| 345 |
+
Returns:
|
| 346 |
+
List of ProfileRow objects, one per (layer, sweep_config) pair.
|
| 347 |
+
Caller persists these into kv_sensitivity_profile.
|
| 348 |
+
|
| 349 |
+
Raises:
|
| 350 |
+
RuntimeError: If the model doesn't expose Llama-family attention.
|
| 351 |
+
Any tokenizer / forward-pass errors propagate.
|
| 352 |
+
"""
|
| 353 |
+
# Local imports β keeps module importable without torch present.
|
| 354 |
+
import torch # noqa: F401
|
| 355 |
+
from kv_intercept import (
|
| 356 |
+
KVQuantSpec,
|
| 357 |
+
find_attention_modules,
|
| 358 |
+
kv_quant_active_multi,
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
def log(msg: str) -> None:
|
| 362 |
+
if progress_cb:
|
| 363 |
+
progress_cb(msg)
|
| 364 |
+
else:
|
| 365 |
+
logger.info(msg)
|
| 366 |
+
|
| 367 |
+
sweep_list = list(sweep)
|
| 368 |
+
if not sweep_list:
|
| 369 |
+
raise ValueError("Empty sweep β at least one SweepConfig required")
|
| 370 |
+
if not calibration_texts:
|
| 371 |
+
raise ValueError("No calibration_texts provided")
|
| 372 |
+
|
| 373 |
+
# ββ 1. Locate attention modules βββββββββββββββββββββββββββββββββββββ
|
| 374 |
+
attn_modules = find_attention_modules(model)
|
| 375 |
+
n_layers = len(attn_modules)
|
| 376 |
+
log(f"[kv-prof] discovered {n_layers} attention layers")
|
| 377 |
+
|
| 378 |
+
# ββ 2. Tokenize calibration set βββββββββββββββοΏ½οΏ½οΏ½βββββββββββββββββββββ
|
| 379 |
+
batch = tokenizer(
|
| 380 |
+
calibration_texts,
|
| 381 |
+
return_tensors="pt",
|
| 382 |
+
padding=True,
|
| 383 |
+
truncation=True,
|
| 384 |
+
max_length=max_seq_len,
|
| 385 |
+
).to(model.device)
|
| 386 |
+
actual_seq_len = batch.input_ids.shape[1]
|
| 387 |
+
log(f"[kv-prof] tokenised {len(calibration_texts)} prompts, "
|
| 388 |
+
f"seq_len={actual_seq_len}")
|
| 389 |
+
|
| 390 |
+
# ββ 3. Compute calibration hash βββββββββββββββββββββββββββββββββββββ
|
| 391 |
+
calibration_hash = compute_calibration_hash(calibration_texts, max_seq_len)
|
| 392 |
+
log(f"[kv-prof] calibration_hash={calibration_hash}")
|
| 393 |
+
|
| 394 |
+
# ββ 4. Capture full-precision baseline attention outputs ββββββββββββ
|
| 395 |
+
log("[kv-prof] capturing fp baseline attention outputs (1 forward pass)")
|
| 396 |
+
t_start = time.time()
|
| 397 |
+
baseline_outputs = _capture_attn_outputs(model, attn_modules, batch)
|
| 398 |
+
log(f"[kv-prof] baseline captured in {time.time() - t_start:.1f}s")
|
| 399 |
+
|
| 400 |
+
if len(baseline_outputs) != n_layers:
|
| 401 |
+
logger.warning(
|
| 402 |
+
"Captured baselines for %d/%d layers β some hooks didn't fire",
|
| 403 |
+
len(baseline_outputs), n_layers,
|
| 404 |
+
)
|
| 405 |
+
|
| 406 |
+
# ββ 5. Per-layer dimensions βββββββββββββββββββββββββββββββββββββββββ
|
| 407 |
+
# Pulled from model.config β Llama-family models report these directly.
|
| 408 |
+
# If a model has per-layer variation (very rare), this is the first
|
| 409 |
+
# place to patch.
|
| 410 |
+
num_kv_heads = getattr(
|
| 411 |
+
model.config, "num_key_value_heads",
|
| 412 |
+
getattr(model.config, "num_attention_heads", 1),
|
| 413 |
+
)
|
| 414 |
+
head_dim = getattr(
|
| 415 |
+
model.config, "head_dim", None,
|
| 416 |
+
) or (model.config.hidden_size // model.config.num_attention_heads)
|
| 417 |
+
log(f"[kv-prof] num_kv_heads={num_kv_heads}, head_dim={head_dim}")
|
| 418 |
+
|
| 419 |
+
# ββ 6. Sweep loop βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 420 |
+
# We sweep per-config (outer loop) and apply the same config to ALL
|
| 421 |
+
# layers simultaneously via kv_quant_active_multi. One forward pass
|
| 422 |
+
# per config, drift measured per-layer from the captured baselines.
|
| 423 |
+
# Total: len(sweep) forward passes, not len(sweep) * n_layers.
|
| 424 |
+
rows: list[ProfileRow] = []
|
| 425 |
+
n_configs = len(sweep_list)
|
| 426 |
+
log(f"[kv-prof] running {n_configs} configs Γ {n_layers} layers "
|
| 427 |
+
f"= {n_configs * n_layers} measurements ({n_configs} forward passes)")
|
| 428 |
+
|
| 429 |
+
profiled_at = datetime.now(UTC).isoformat()
|
| 430 |
+
|
| 431 |
+
for cfg_idx, cfg in enumerate(sweep_list):
|
| 432 |
+
log(f"[kv-prof] config {cfg_idx + 1}/{n_configs}: "
|
| 433 |
+
f"k={cfg.k_bits}b v={cfg.v_bits}b {cfg.quantizer}")
|
| 434 |
+
t_cfg = time.time()
|
| 435 |
+
|
| 436 |
+
spec = KVQuantSpec(
|
| 437 |
+
k_bits=cfg.k_bits,
|
| 438 |
+
v_bits=cfg.v_bits,
|
| 439 |
+
quantizer=cfg.quantizer,
|
| 440 |
+
group_size=cfg.group_size,
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
# Special case: fp16_passthrough is the baseline β drift is
|
| 444 |
+
# definitionally zero. Skip the forward pass.
|
| 445 |
+
if cfg.quantizer == "fp16_passthrough":
|
| 446 |
+
quanted_outputs = baseline_outputs
|
| 447 |
+
else:
|
| 448 |
+
specs_by_layer = {li: spec for li in attn_modules}
|
| 449 |
+
with kv_quant_active_multi(attn_modules, specs_by_layer):
|
| 450 |
+
quanted_outputs = _capture_attn_outputs(
|
| 451 |
+
model, attn_modules, batch,
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
# Per-layer bytes_per_token at this config (constant across layers
|
| 455 |
+
# in uniform-arch models; computed per-layer in case of variation)
|
| 456 |
+
bpt = kv_bytes_per_token(
|
| 457 |
+
num_kv_heads=num_kv_heads,
|
| 458 |
+
head_dim=head_dim,
|
| 459 |
+
k_bits=cfg.k_bits,
|
| 460 |
+
v_bits=cfg.v_bits,
|
| 461 |
+
quantizer=cfg.quantizer,
|
| 462 |
+
group_size=cfg.group_size,
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
# Compute drift for every layer at this config
|
| 466 |
+
for li in attn_modules:
|
| 467 |
+
if li not in quanted_outputs or li not in baseline_outputs:
|
| 468 |
+
logger.debug("layer %d: missing capture, skipping", li)
|
| 469 |
+
continue
|
| 470 |
+
drift = compute_drift(
|
| 471 |
+
quanted_outputs[li],
|
| 472 |
+
baseline_outputs[li],
|
| 473 |
+
drift_metric,
|
| 474 |
+
)
|
| 475 |
+
rows.append(ProfileRow(
|
| 476 |
+
model_hash=model_hash,
|
| 477 |
+
calibration_hash=calibration_hash,
|
| 478 |
+
pipeline_version=pipeline_version,
|
| 479 |
+
layer_idx=li,
|
| 480 |
+
k_bits=cfg.k_bits,
|
| 481 |
+
v_bits=cfg.v_bits,
|
| 482 |
+
quantizer=cfg.quantizer,
|
| 483 |
+
drift_attn_output=float(drift),
|
| 484 |
+
drift_metric=drift_metric,
|
| 485 |
+
bytes_per_kv_token=float(bpt),
|
| 486 |
+
max_seq_len_observed=actual_seq_len,
|
| 487 |
+
num_kv_heads=num_kv_heads,
|
| 488 |
+
head_dim=head_dim,
|
| 489 |
+
profiled_at=profiled_at,
|
| 490 |
+
profiled_by_agent_id=profiled_by_agent_id,
|
| 491 |
+
profiled_by_agent_tier=profiled_by_agent_tier,
|
| 492 |
+
))
|
| 493 |
+
|
| 494 |
+
log(f"[kv-prof] config done in {time.time() - t_cfg:.1f}s, "
|
| 495 |
+
f"sample drift = {rows[-1].drift_attn_output:.4e}")
|
| 496 |
+
|
| 497 |
+
log(f"[kv-prof] complete β {len(rows)} rows total")
|
| 498 |
+
return rows
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
# ---------------------------------------------------------------------------
|
| 502 |
+
# Bridge to allocator
|
| 503 |
+
# ---------------------------------------------------------------------------
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
def rows_to_kv_candidates(rows: list[ProfileRow]):
|
| 507 |
+
"""Group ProfileRows by layer into KVCandidate objects that
|
| 508 |
+
assign_kv_bits (in assignment_v2.py) consumes directly.
|
| 509 |
+
|
| 510 |
+
Carries num_kv_heads and head_dim through from the rows so the
|
| 511 |
+
allocator gets the real per-layer dimensions, not placeholders.
|
| 512 |
+
"""
|
| 513 |
+
from assignment_v2 import KVCandidate, KVOption
|
| 514 |
+
from collections import defaultdict
|
| 515 |
+
|
| 516 |
+
by_layer: dict[int, list[ProfileRow]] = defaultdict(list)
|
| 517 |
+
for r in rows:
|
| 518 |
+
by_layer[r.layer_idx].append(r)
|
| 519 |
+
|
| 520 |
+
candidates = []
|
| 521 |
+
for layer_idx, layer_rows in sorted(by_layer.items()):
|
| 522 |
+
# All rows for one layer share num_kv_heads/head_dim by construction
|
| 523 |
+
first = layer_rows[0]
|
| 524 |
+
options = [
|
| 525 |
+
KVOption(
|
| 526 |
+
k_bits=r.k_bits,
|
| 527 |
+
v_bits=r.v_bits,
|
| 528 |
+
quantizer=r.quantizer,
|
| 529 |
+
drift=r.drift_attn_output,
|
| 530 |
+
bytes_per_kv_token=r.bytes_per_kv_token,
|
| 531 |
+
)
|
| 532 |
+
for r in layer_rows
|
| 533 |
+
]
|
| 534 |
+
candidates.append(KVCandidate(
|
| 535 |
+
layer_idx=layer_idx,
|
| 536 |
+
num_kv_heads=first.num_kv_heads,
|
| 537 |
+
head_dim=first.head_dim,
|
| 538 |
+
options=options,
|
| 539 |
+
))
|
| 540 |
+
return candidates
|