| """ |
| HSAQ Phase-1 Sensitivity Profiler β Hessian-diag + Activation Magnitude |
| (Note: HF Jobs UV-runner is at mxguru1/hsaq-sensitivity-profiles/runners/profile_granite_8b.py) |
| ======================================================================== |
| |
| Standalone module per 2026-05-19 plan. Produces a JSON dict of |
| {layer_name: scores} for granite-3.3-8b (or any HF causal-LM) using a single |
| calibration pass. |
| |
| Two signals combined per channel, then top-decile-mean'd to a layer score: |
| - Hessian-diag proxy: sum_i (x_i^2) # input variance per channel |
| - Activation magnitude: max_i |x_i| # AWQ-style outlier presence |
| |
| Diagonal-only Hessian: state per layer is [in_features], not [in_features, in_features]. |
| For ~280 linear layers on granite-8B at hidden=4096, peak hook state is ~16 MB, |
| not ~18 GB. |
| |
| This is NOT wired into HSAQ assignment.py. Phase-1 deliverable is the JSON only β |
| integration shape (sensitivity floor / quantizer routing / weighted greedy) is |
| deferred until we eyeball the scores. |
| |
| Run: |
| python profile_sensitivity.py \\ |
| --model ibm-granite/granite-3.3-8b-instruct \\ |
| --calib-dataset mxguru1/master-chief-benign-calibration-v1 \\ |
| --n-samples 32 --seq-len 512 \\ |
| --out sensitivity_scores_granite_8b.json |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import logging |
| import re |
| import time |
| from dataclasses import asdict, dataclass |
| from pathlib import Path |
| from typing import Iterable |
|
|
| import torch |
| import torch.nn as nn |
|
|
| logger = logging.getLogger("hsaq.profile_sensitivity") |
| PIPELINE_VERSION = "profile_sensitivity.v0.1.0" |
|
|
| |
| |
| |
| LAYER_NAME_RE = re.compile(r"\.layers\.\d+\.(self_attn|mlp)\.[a-z_]+_proj$") |
|
|
| |
| |
| MIN_IN_FEATURES_FOR_TOPK = 256 |
|
|
|
|
| @dataclass |
| class LayerScore: |
| layer_name: str |
| layer_idx: int |
| layer_type: str |
| in_features: int |
| hess_diag_score: float |
| act_max_score: float |
| combined_score: float |
| aggregator: str |
| finite: bool |
| n_token_positions: int |
|
|
|
|
| def _parse_layer_idx(name: str) -> int: |
| m = re.search(r"\.layers\.(\d+)\.", name) |
| return int(m.group(1)) if m else -1 |
|
|
|
|
| def _layer_type(name: str) -> str: |
| return name.rsplit(".", 1)[-1] |
|
|
|
|
| def _select_target_layers(model: nn.Module) -> dict[str, nn.Linear]: |
| targets: dict[str, nn.Linear] = {} |
| for name, mod in model.named_modules(): |
| if not isinstance(mod, nn.Linear): |
| continue |
| if not LAYER_NAME_RE.search(name): |
| continue |
| targets[name] = mod |
| return targets |
|
|
|
|
| def _safe_max(t: torch.Tensor) -> float: |
| finite = t[torch.isfinite(t)] |
| return float(finite.max().item()) if finite.numel() > 0 else 0.0 |
|
|
|
|
| def _combine_to_layer_score( |
| hess_diag: torch.Tensor, |
| act_max: torch.Tensor, |
| in_features: int, |
| hess_weight: float = 0.6, |
| act_weight: float = 0.4, |
| ) -> tuple[float, float, float, str]: |
| hess_norm = hess_diag / (hess_diag.max() + 1e-8) |
| act_norm = act_max / (act_max.max() + 1e-8) |
| combined = hess_weight * hess_norm + act_weight * act_norm |
|
|
| hess_s = float(hess_norm.mean().item()) |
| act_s = float(act_norm.mean().item()) |
|
|
| if in_features < MIN_IN_FEATURES_FOR_TOPK: |
| score = float(combined.max().item()) |
| aggregator = "max" |
| else: |
| k = max(1, combined.numel() // 10) |
| score = float(combined.topk(k).values.mean().item()) |
| aggregator = "topk_mean" |
|
|
| return hess_s, act_s, score, aggregator |
|
|
|
|
| def profile_sensitivity_unified( |
| model: nn.Module, |
| calib_iter: Iterable[dict], |
| n_samples: int, |
| device: str = "cuda", |
| ) -> list[LayerScore]: |
| """Single calibration pass β all target layers profiled simultaneously.""" |
| targets = _select_target_layers(model) |
| if not targets: |
| raise RuntimeError( |
| "No target layers matched the filter. " |
| "Check LAYER_NAME_RE against this model's module names." |
| ) |
|
|
| logger.info("Hooking %d target layers", len(targets)) |
|
|
| state: dict[str, dict] = {} |
| for name, mod in targets.items(): |
| in_dim = mod.in_features |
| state[name] = { |
| "H_diag": torch.zeros(in_dim, device=device, dtype=torch.float32), |
| "max": torch.zeros(in_dim, device=device, dtype=torch.float32), |
| "n_seen": 0, |
| "in_features": in_dim, |
| } |
|
|
| handles = [] |
|
|
| def make_hook(layer_name: str): |
| def hook(module, input_tuple, output): |
| x = input_tuple[0].detach().to(torch.float32) |
| x = x.reshape(-1, x.shape[-1]) |
| s = state[layer_name] |
| s["H_diag"].add_((x * x).sum(dim=0)) |
| torch.maximum(s["max"], x.abs().amax(dim=0), out=s["max"]) |
| s["n_seen"] += x.shape[0] |
| return hook |
|
|
| |
| |
| |
| for name, mod in targets.items(): |
| handles.append(mod.register_forward_hook(make_hook(name))) |
|
|
| try: |
| model.eval() |
| with torch.no_grad(): |
| consumed = 0 |
| for i, batch in enumerate(calib_iter): |
| if i >= n_samples: |
| break |
| input_ids = batch["input_ids"].to(device) |
| model(input_ids=input_ids) |
| consumed = i + 1 |
| if consumed % 8 == 0: |
| logger.info("Calibration batch %d/%d", consumed, n_samples) |
| logger.info("Calibration loop consumed %d/%d batches", consumed, n_samples) |
| finally: |
| for h in handles: |
| h.remove() |
|
|
| scores: list[LayerScore] = [] |
| for name, s in state.items(): |
| n_seen = max(s["n_seen"], 1) |
| H_diag = s["H_diag"] / n_seen |
| act_max = s["max"] |
|
|
| |
| |
| finite_h = torch.isfinite(H_diag).all().item() |
| finite_a = torch.isfinite(act_max).all().item() |
| finite = bool(finite_h and finite_a) |
| if not finite: |
| logger.warning("Non-finite values in %s β clamping (h=%s a=%s)", name, finite_h, finite_a) |
| H_diag = torch.nan_to_num(H_diag, nan=0.0, posinf=_safe_max(H_diag), neginf=0.0) |
| act_max = torch.nan_to_num(act_max, nan=0.0, posinf=_safe_max(act_max), neginf=0.0) |
|
|
| hess_s, act_s, combined_s, aggregator = _combine_to_layer_score( |
| H_diag.cpu(), act_max.cpu(), s["in_features"] |
| ) |
| scores.append(LayerScore( |
| layer_name=name, |
| layer_idx=_parse_layer_idx(name), |
| layer_type=_layer_type(name), |
| in_features=s["in_features"], |
| hess_diag_score=hess_s, |
| act_max_score=act_s, |
| combined_score=combined_s, |
| aggregator=aggregator, |
| finite=finite, |
| n_token_positions=s["n_seen"], |
| )) |
|
|
| scores.sort(key=lambda r: (r.layer_idx, r.layer_type)) |
| return scores |
|
|
|
|
| def _build_calib_iter(dataset, tokenizer, seq_len: int, batch_size: int): |
| """Concatenate dataset[text] into a token stream, chunk into seq_len blocks, |
| yield as batches of input_ids.""" |
| eos = tokenizer.eos_token_id if tokenizer.eos_token_id is not None else 0 |
| buf: list[int] = [] |
| for row in dataset: |
| text = row.get("text") or row.get("prompt") or "" |
| if not text: |
| continue |
| ids = tokenizer(text, add_special_tokens=False)["input_ids"] |
| buf.extend(ids) |
| buf.append(eos) |
|
|
| n_full = (len(buf) // seq_len) * seq_len |
| blocks = [buf[i:i + seq_len] for i in range(0, n_full, seq_len)] |
| logger.info("Built %d blocks of %d tokens from %d total tokens", len(blocks), seq_len, len(buf)) |
|
|
| for i in range(0, (len(blocks) // batch_size) * batch_size, batch_size): |
| chunk = blocks[i:i + batch_size] |
| yield {"input_ids": torch.tensor(chunk, dtype=torch.long)} |
|
|
|
|
| def main(): |
| p = argparse.ArgumentParser() |
| p.add_argument("--model", default="ibm-granite/granite-3.3-8b-instruct") |
| p.add_argument("--calib-dataset", default="mxguru1/master-chief-benign-calibration-v1") |
| p.add_argument("--calib-split", default="train") |
| p.add_argument("--n-samples", type=int, default=32) |
| p.add_argument("--seq-len", type=int, default=512) |
| p.add_argument("--batch-size", type=int, default=1) |
| p.add_argument("--out", default="sensitivity_scores.json") |
| p.add_argument("--device", default="cuda") |
| p.add_argument("--dtype", default="bfloat16", choices=["bfloat16", "float16", "float32"]) |
| args = p.parse_args() |
|
|
| logging.basicConfig( |
| level=logging.INFO, |
| format="%(asctime)s %(levelname)s %(name)s: %(message)s", |
| ) |
|
|
| from datasets import load_dataset |
| from transformers import AutoModelForCausalLM, AutoTokenizer |
|
|
| dtype = {"bfloat16": torch.bfloat16, "float16": torch.float16, "float32": torch.float32}[args.dtype] |
|
|
| logger.info("Loading tokenizer: %s", args.model) |
| tok = AutoTokenizer.from_pretrained(args.model) |
| if tok.pad_token_id is None: |
| tok.pad_token = tok.eos_token |
|
|
| logger.info("Loading model: %s (dtype=%s, device=%s)", args.model, args.dtype, args.device) |
| model = AutoModelForCausalLM.from_pretrained(args.model, torch_dtype=dtype) |
| model.to(args.device) |
| model.eval() |
|
|
| logger.info("Loading calibration set: %s [%s]", args.calib_dataset, args.calib_split) |
| ds = load_dataset(args.calib_dataset, split=args.calib_split) |
| logger.info("Calibration set: %d rows", len(ds)) |
|
|
| calib_iter = _build_calib_iter(ds, tok, seq_len=args.seq_len, batch_size=args.batch_size) |
|
|
| t0 = time.time() |
| scores = profile_sensitivity_unified( |
| model=model, |
| calib_iter=calib_iter, |
| n_samples=args.n_samples, |
| device=args.device, |
| ) |
| elapsed = time.time() - t0 |
| logger.info("Profiling complete in %.1fs (%d layers)", elapsed, len(scores)) |
|
|
| payload = { |
| "pipeline_version": PIPELINE_VERSION, |
| "model": args.model, |
| "calibration_dataset": args.calib_dataset, |
| "calibration_split": args.calib_split, |
| "n_samples_requested": args.n_samples, |
| "seq_len": args.seq_len, |
| "batch_size": args.batch_size, |
| "dtype": args.dtype, |
| "elapsed_seconds": elapsed, |
| "n_layers": len(scores), |
| "layers": [asdict(s) for s in scores], |
| } |
| Path(args.out).write_text(json.dumps(payload, indent=2)) |
| logger.info("Wrote scores to %s", args.out) |
|
|
| by_type: dict[str, list[float]] = {} |
| for s in scores: |
| by_type.setdefault(s.layer_type, []).append(s.combined_score) |
| print("\n=== Mean combined_score by layer_type ===") |
| for lt, vals in sorted(by_type.items(), key=lambda kv: -sum(kv[1]) / max(1, len(kv[1]))): |
| mean = sum(vals) / len(vals) |
| print(f" {lt:12s} mean={mean:.4f} n={len(vals)}") |
|
|
| top10 = sorted(scores, key=lambda r: -r.combined_score)[:10] |
| bot10 = sorted(scores, key=lambda r: r.combined_score)[:10] |
| print("\n=== Top 10 layers by combined_score ===") |
| for s in top10: |
| print(f" {s.combined_score:.4f} L{s.layer_idx:02d} {s.layer_type}") |
| print("\n=== Bottom 10 layers by combined_score ===") |
| for s in bot10: |
| print(f" {s.combined_score:.4f} L{s.layer_idx:02d} {s.layer_type}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|
|
|
| |
|
|
| def build_floor_from_scores_json( |
| scores_path: str | Path, |
| top_n: int | None = None, |
| score_threshold: float | None = None, |
| layer_type_filter: str | tuple[str, ...] | None = None, |
| min_bits: int = 4, |
| ) -> dict[str, int]: |
| """Build a min_bits_floor map for assign_bit_widths from a sensitivity JSON. |
| |
| Parameters |
| ---------- |
| scores_path : path to a sensitivity_scores_*.json produced by main() |
| top_n : if set, pick top-N layers by combined_score (after layer_type_filter) |
| score_threshold : if set, pick all layers with combined_score >= threshold |
| layer_type_filter : keep only these layer types (e.g. ("o_proj",) or "o_proj") |
| min_bits : the floor value to apply to picked layers |
| |
| Returns |
| ------- |
| {component_name: min_bits} β keys match LayerCandidate.component (full module name) |
| """ |
| if top_n is None and score_threshold is None: |
| raise ValueError("Specify top_n or score_threshold") |
|
|
| payload = json.loads(Path(scores_path).read_text()) |
| layers = payload["layers"] |
|
|
| if layer_type_filter is not None: |
| if isinstance(layer_type_filter, str): |
| layer_type_filter = (layer_type_filter,) |
| layers = [l for l in layers if l["layer_type"] in layer_type_filter] |
|
|
| if score_threshold is not None: |
| layers = [l for l in layers if l["combined_score"] >= score_threshold] |
|
|
| if top_n is not None: |
| layers = sorted(layers, key=lambda l: -l["combined_score"])[:top_n] |
|
|
| return {l["layer_name"]: min_bits for l in layers} |
|
|