| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| """ |
| Phase-3a drift-inversion transfer test → microsoft/phi-4 (14B, MHA) |
| ==================================================================== |
| Question: does the granite-8B drift-inversion finding (forcing o_proj layers |
| from 3-bit to 4-bit improves PPL despite worse drift scores) reproduce on |
| a different architecture and model family? |
| |
| Design (single-job two-pass): |
| 1. Load phi-4 bf16 → cuda |
| 2. HSAQ profile + assign (no floor) → baseline name_to_bits |
| 3. Identify any `o_proj` layers landing at 3-bit in baseline |
| 4. Save bf16 weights of those o_proj layers |
| 5. HQQ everything except those o_proj layers per baseline assignment |
| 6. HQQ those o_proj layers at 3-bit |
| 7. Full-set wikitext-2 PPL → ppl_baseline |
| 8. Reinstall bf16 on those o_proj layers, HQQ them at 4-bit (floor) |
| 9. Full-set wikitext-2 PPL → ppl_floor |
| 10. Report delta. Positive delta = drift-inversion confirmed on phi-4. |
| |
| If no o_proj layers land at 3-bit in baseline, the test is moot — report |
| that as the outcome (transfer-not-applicable). |
| |
| Cost: ~$3, ~50 min on A100 80GB. |
| """ |
| from __future__ import annotations |
| import json, logging, os, statistics, subprocess, sys, time |
| from datetime import UTC, datetime |
| from pathlib import Path |
| import torch |
|
|
| if not torch.cuda.is_available(): |
| subprocess.check_call([sys.executable, "-m", "pip", "install", "torch", "--force-reinstall", |
| "--index-url", "https://download.pytorch.org/whl/cu124"]) |
| import importlib; importlib.reload(torch) |
| if not torch.cuda.is_available(): sys.exit(1) |
|
|
| logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s | %(message)s") |
| logger = logging.getLogger("Phi4Transfer") |
|
|
| sys.path.insert(0, "/opt/hsaq") |
| from quantization.hsaq.config import HSAQConfig |
| from quantization.hsaq.pipeline import HSAQPipeline |
|
|
| MODEL_ID = "microsoft/phi-4" |
| HF_TOKEN = os.environ.get("HF_TOKEN") |
| RUN_TAG = datetime.now(UTC).strftime("%Y%m%d_%H%M%S") |
| OUT = Path("/tmp/phi4_transfer"); OUT.mkdir(parents=True, exist_ok=True) |
| HQQ_GROUP_SIZE = 64 |
|
|
|
|
| def evaluate_ppl(model, tokenizer, ctx_len: int = 2048) -> tuple[float, int, list[float]]: |
| from datasets import load_dataset |
| ds = load_dataset("wikitext", "wikitext-2-raw-v1", split="test") |
| text = "\n\n".join(ds["text"]) |
| enc = tokenizer(text, return_tensors="pt", truncation=False) |
| input_ids = enc.input_ids.to("cuda:0") |
| nlls = [] |
| per_window = [] |
| stride = ctx_len |
| prev_end = 0 |
| n = 0 |
| for i in range(0, input_ids.size(1), stride): |
| begin = max(i + stride - ctx_len, 0) |
| end = min(i + stride, input_ids.size(1)) |
| trg_len = end - prev_end |
| ids = input_ids[:, begin:end] |
| target = ids.clone() |
| target[:, :-trg_len] = -100 |
| with torch.no_grad(): |
| out = model(ids, labels=target) |
| nlls.append(out.loss.float() * trg_len) |
| per_window.append(float(torch.exp(out.loss.float()).item())) |
| prev_end = end |
| n += 1 |
| return float(torch.exp(torch.stack(nlls).sum() / end).item()), n, per_window |
|
|
|
|
| def _set_submodule(model, name, new_mod): |
| if "." in name: |
| parent_name, attr = name.rsplit(".", 1) |
| parent = model.get_submodule(parent_name) |
| else: |
| parent, attr = model, name |
| setattr(parent, attr, new_mod) |
|
|
|
|
| def apply_hqq_one(model, name, nbits): |
| from hqq.core.quantize import BaseQuantizeConfig, HQQLinear |
| mod = model.get_submodule(name) |
| cfg = BaseQuantizeConfig(nbits=nbits, group_size=HQQ_GROUP_SIZE, axis=0) |
| hqq = HQQLinear(mod, cfg, compute_dtype=torch.bfloat16, device="cuda:0", del_orig=True) |
| _set_submodule(model, name, hqq) |
|
|
|
|
| def reinstall_bf16(model, name, W_bf16, bias_or_none, in_f, out_f): |
| new_linear = torch.nn.Linear(in_f, out_f, bias=bias_or_none is not None, dtype=torch.bfloat16) |
| new_linear = new_linear.to("cuda:0") |
| with torch.no_grad(): |
| new_linear.weight.copy_(W_bf16.to(torch.bfloat16).to("cuda:0")) |
| if bias_or_none is not None: |
| new_linear.bias.copy_(bias_or_none.to(torch.bfloat16).to("cuda:0")) |
| _set_submodule(model, name, new_linear) |
|
|
|
|
| def upload_report(report): |
| from huggingface_hub import HfApi |
| repo_id = f"mxguru1/phi4-drift-transfer-{RUN_TAG}" |
| api = HfApi(token=HF_TOKEN) |
| api.create_repo(repo_id=repo_id, repo_type="dataset", exist_ok=True) |
| p = OUT / "report.json"; p.write_text(json.dumps(report, indent=2)) |
| api.upload_file(path_or_fileobj=str(p), path_in_repo="report.json", |
| repo_id=repo_id, repo_type="dataset") |
| logger.info("Report uploaded: https://huggingface.co/datasets/%s", repo_id) |
|
|
|
|
| def main(): |
| start = time.time() |
| report = { |
| "run_tag": RUN_TAG, |
| "approach": "phase3a_drift_inversion_transfer_to_phi4", |
| "model_id": MODEL_ID, |
| "intervention": "force o_proj layers at 3-bit to 4-bit", |
| "eval_protocol": "wikitext-2-raw-v1/test, full set, ctx=2048, stride=2048", |
| } |
| try: |
| cfg = HSAQConfig( |
| model_id=MODEL_ID, |
| output_dir=str(OUT.parent), |
| hf_token=HF_TOKEN, |
| gpu_budget_gb=11.2, |
| enable_2bit=False, |
| enable_pruning=False, |
| train_lora=False, |
| calibration_samples=128, |
| ) |
| pipe = HSAQPipeline(cfg) |
| logger.info("Stage 1: load + profile phi-4") |
| model, tokenizer = pipe._load_model() |
| model = model.to("cuda:0") |
| if tokenizer.pad_token is None: |
| tokenizer.pad_token = tokenizer.eos_token |
|
|
| sensitivity = pipe.profiler.profile(model) |
| candidates = pipe._build_layer_candidates(sensitivity, model) |
| from quantization.hsaq.assignment import assign_bit_widths |
| weight_budget_gb = pipe._compute_weight_budget() |
| baseline_assignment = assign_bit_widths(candidates, weight_budget_gb) |
| name_to_bits = {a.component: a.chosen.bits for a in baseline_assignment.assignments} |
|
|
| |
| o_proj_3bit = sorted([n for n, b in name_to_bits.items() if b == 3 and "o_proj" in n]) |
| logger.info("o_proj layers at 3-bit in baseline assignment: %d", len(o_proj_3bit)) |
| for n in o_proj_3bit: |
| logger.info(" %s", n) |
| report["o_proj_3bit_count"] = len(o_proj_3bit) |
| report["o_proj_3bit_layers"] = o_proj_3bit |
|
|
| |
| residue = sorted([n for n, b in name_to_bits.items() if b == 3]) |
| report["full_3bit_residue_count"] = len(residue) |
| report["full_3bit_residue"] = residue |
|
|
| if not o_proj_3bit: |
| logger.info("No o_proj at 3-bit — transfer test not applicable on phi-4") |
| report["status"] = "transfer_not_applicable" |
| report["reason"] = "No o_proj layers landed at 3-bit in baseline assignment" |
| |
| n_hqq = pipe._apply_per_module_hqq(model, name_to_bits, device="cuda:0") |
| logger.info("HQQ applied to %d Linears", n_hqq) |
| ppl, n_w, pw = evaluate_ppl(model, tokenizer) |
| report["ppl_baseline_no_floor"] = ppl |
| report["n_windows"] = n_w |
| return |
|
|
| |
| o_proj_bf16, o_proj_bias, o_proj_shape = {}, {}, {} |
| for name in o_proj_3bit: |
| mod = model.get_submodule(name) |
| o_proj_bf16[name] = mod.weight.detach().clone().cpu() |
| o_proj_bias[name] = None if mod.bias is None else mod.bias.detach().clone().cpu() |
| o_proj_shape[name] = (mod.in_features, mod.out_features) |
|
|
| |
| non_target_bits = {n: b for n, b in name_to_bits.items() if n not in o_proj_3bit} |
| n_hqq = pipe._apply_per_module_hqq(model, non_target_bits, device="cuda:0") |
| logger.info("HQQ applied to %d non-target Linears", n_hqq) |
|
|
| |
| logger.info("=== PASS 1: baseline (o_proj at 3-bit) ===") |
| for name in o_proj_3bit: |
| apply_hqq_one(model, name, nbits=3) |
| ppl_baseline, n_w, pw_baseline = evaluate_ppl(model, tokenizer) |
| logger.info("Pass 1 PPL: %.4f", ppl_baseline) |
|
|
| |
| logger.info("=== PASS 2: floor (o_proj at 4-bit) ===") |
| for name in o_proj_3bit: |
| in_f, out_f = o_proj_shape[name] |
| reinstall_bf16(model, name, o_proj_bf16[name], o_proj_bias[name], in_f, out_f) |
| apply_hqq_one(model, name, nbits=4) |
| ppl_floor, _, pw_floor = evaluate_ppl(model, tokenizer) |
| logger.info("Pass 2 PPL: %.4f", ppl_floor) |
|
|
| delta_abs = ppl_baseline - ppl_floor |
| delta_pct = (ppl_baseline - ppl_floor) / ppl_baseline * 100 |
| report["result"] = { |
| "ppl_baseline": ppl_baseline, |
| "ppl_floor": ppl_floor, |
| "delta_abs": delta_abs, |
| "delta_pct": delta_pct, |
| "n_windows": n_w, |
| "per_window_baseline": pw_baseline, |
| "per_window_floor": pw_floor, |
| } |
| report["status"] = "success" |
| logger.info("=" * 60) |
| logger.info("PHI-4 DRIFT-INVERSION TRANSFER:") |
| logger.info(" baseline (o_proj@3): %.4f", ppl_baseline) |
| logger.info(" floor (o_proj@4): %.4f", ppl_floor) |
| logger.info(" delta: %.4f (%+.3f%%) %s", delta_abs, -delta_pct, |
| "← drift-inversion confirmed" if delta_abs > 0 else "← does not transfer") |
| logger.info("=" * 60) |
| except Exception as e: |
| logger.exception("Run failed") |
| report["status"] = "failed" |
| report["error"] = repr(e) |
| finally: |
| report["elapsed_s"] = round(time.time() - start, 1) |
| upload_report(report) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|