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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.11"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "torch>=2.1,<2.7",
|
| 5 |
+
# "transformers>=4.46,<4.50",
|
| 6 |
+
# "datasets",
|
| 7 |
+
# "hqq>=0.2.8",
|
| 8 |
+
# "accelerate",
|
| 9 |
+
# "tqdm",
|
| 10 |
+
# "huggingface_hub",
|
| 11 |
+
# ]
|
| 12 |
+
# ///
|
| 13 |
+
"""
|
| 14 |
+
Phase-3a drift-inversion transfer test → Qwen/Qwen2.5-14B-Instruct (14B, MHA)
|
| 15 |
+
====================================================================
|
| 16 |
+
Question: does the granite-8B drift-inversion finding (forcing o_proj layers
|
| 17 |
+
from 3-bit to 4-bit improves PPL despite worse drift scores) reproduce on
|
| 18 |
+
a different architecture and model family?
|
| 19 |
+
|
| 20 |
+
Design (single-job two-pass):
|
| 21 |
+
1. Load phi-4 bf16 → cuda
|
| 22 |
+
2. HSAQ profile + assign (no floor) → baseline name_to_bits
|
| 23 |
+
3. Identify any `o_proj` layers landing at 3-bit in baseline
|
| 24 |
+
4. Save bf16 weights of those o_proj layers
|
| 25 |
+
5. HQQ everything except those o_proj layers per baseline assignment
|
| 26 |
+
6. HQQ those o_proj layers at 3-bit
|
| 27 |
+
7. Full-set wikitext-2 PPL → ppl_baseline
|
| 28 |
+
8. Reinstall bf16 on those o_proj layers, HQQ them at 4-bit (floor)
|
| 29 |
+
9. Full-set wikitext-2 PPL → ppl_floor
|
| 30 |
+
10. Report delta. Positive delta = drift-inversion confirmed on phi-4.
|
| 31 |
+
|
| 32 |
+
If no o_proj layers land at 3-bit in baseline, the test is moot — report
|
| 33 |
+
that as the outcome (transfer-not-applicable).
|
| 34 |
+
|
| 35 |
+
Cost: ~$3, ~50 min on A100 80GB.
|
| 36 |
+
"""
|
| 37 |
+
from __future__ import annotations
|
| 38 |
+
import json, logging, os, statistics, subprocess, sys, time
|
| 39 |
+
from datetime import UTC, datetime
|
| 40 |
+
from pathlib import Path
|
| 41 |
+
import torch
|
| 42 |
+
|
| 43 |
+
if not torch.cuda.is_available():
|
| 44 |
+
subprocess.check_call([sys.executable, "-m", "pip", "install", "torch", "--force-reinstall",
|
| 45 |
+
"--index-url", "https://download.pytorch.org/whl/cu124"])
|
| 46 |
+
import importlib; importlib.reload(torch)
|
| 47 |
+
if not torch.cuda.is_available(): sys.exit(1)
|
| 48 |
+
|
| 49 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s | %(message)s")
|
| 50 |
+
logger = logging.getLogger("QwenTransfer")
|
| 51 |
+
|
| 52 |
+
sys.path.insert(0, "/opt/hsaq")
|
| 53 |
+
from quantization.hsaq.config import HSAQConfig
|
| 54 |
+
from quantization.hsaq.pipeline import HSAQPipeline
|
| 55 |
+
|
| 56 |
+
MODEL_ID = "Qwen/Qwen2.5-14B-Instruct"
|
| 57 |
+
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 58 |
+
RUN_TAG = datetime.now(UTC).strftime("%Y%m%d_%H%M%S")
|
| 59 |
+
OUT = Path("/tmp/qwen_transfer"); OUT.mkdir(parents=True, exist_ok=True)
|
| 60 |
+
HQQ_GROUP_SIZE = 64
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def evaluate_ppl(model, tokenizer, ctx_len: int = 2048) -> tuple[float, int, list[float]]:
|
| 64 |
+
from datasets import load_dataset
|
| 65 |
+
ds = load_dataset("wikitext", "wikitext-2-raw-v1", split="test")
|
| 66 |
+
text = "\n\n".join(ds["text"])
|
| 67 |
+
enc = tokenizer(text, return_tensors="pt", truncation=False)
|
| 68 |
+
input_ids = enc.input_ids.to("cuda:0")
|
| 69 |
+
nlls = []
|
| 70 |
+
per_window = []
|
| 71 |
+
stride = ctx_len
|
| 72 |
+
prev_end = 0
|
| 73 |
+
n = 0
|
| 74 |
+
for i in range(0, input_ids.size(1), stride):
|
| 75 |
+
begin = max(i + stride - ctx_len, 0)
|
| 76 |
+
end = min(i + stride, input_ids.size(1))
|
| 77 |
+
trg_len = end - prev_end
|
| 78 |
+
ids = input_ids[:, begin:end]
|
| 79 |
+
target = ids.clone()
|
| 80 |
+
target[:, :-trg_len] = -100
|
| 81 |
+
with torch.no_grad():
|
| 82 |
+
out = model(ids, labels=target)
|
| 83 |
+
nlls.append(out.loss.float() * trg_len)
|
| 84 |
+
per_window.append(float(torch.exp(out.loss.float()).item()))
|
| 85 |
+
prev_end = end
|
| 86 |
+
n += 1
|
| 87 |
+
return float(torch.exp(torch.stack(nlls).sum() / end).item()), n, per_window
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _set_submodule(model, name, new_mod):
|
| 91 |
+
if "." in name:
|
| 92 |
+
parent_name, attr = name.rsplit(".", 1)
|
| 93 |
+
parent = model.get_submodule(parent_name)
|
| 94 |
+
else:
|
| 95 |
+
parent, attr = model, name
|
| 96 |
+
setattr(parent, attr, new_mod)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def apply_hqq_one(model, name, nbits):
|
| 100 |
+
from hqq.core.quantize import BaseQuantizeConfig, HQQLinear
|
| 101 |
+
mod = model.get_submodule(name)
|
| 102 |
+
cfg = BaseQuantizeConfig(nbits=nbits, group_size=HQQ_GROUP_SIZE, axis=0)
|
| 103 |
+
hqq = HQQLinear(mod, cfg, compute_dtype=torch.bfloat16, device="cuda:0", del_orig=True)
|
| 104 |
+
_set_submodule(model, name, hqq)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def reinstall_bf16(model, name, W_bf16, bias_or_none, in_f, out_f):
|
| 108 |
+
new_linear = torch.nn.Linear(in_f, out_f, bias=bias_or_none is not None, dtype=torch.bfloat16)
|
| 109 |
+
new_linear = new_linear.to("cuda:0")
|
| 110 |
+
with torch.no_grad():
|
| 111 |
+
new_linear.weight.copy_(W_bf16.to(torch.bfloat16).to("cuda:0"))
|
| 112 |
+
if bias_or_none is not None:
|
| 113 |
+
new_linear.bias.copy_(bias_or_none.to(torch.bfloat16).to("cuda:0"))
|
| 114 |
+
_set_submodule(model, name, new_linear)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def upload_report(report):
|
| 118 |
+
from huggingface_hub import HfApi
|
| 119 |
+
repo_id = f"mxguru1/qwen-drift-transfer-{RUN_TAG}"
|
| 120 |
+
api = HfApi(token=HF_TOKEN)
|
| 121 |
+
api.create_repo(repo_id=repo_id, repo_type="dataset", exist_ok=True)
|
| 122 |
+
p = OUT / "report.json"; p.write_text(json.dumps(report, indent=2))
|
| 123 |
+
api.upload_file(path_or_fileobj=str(p), path_in_repo="report.json",
|
| 124 |
+
repo_id=repo_id, repo_type="dataset")
|
| 125 |
+
logger.info("Report uploaded: https://huggingface.co/datasets/%s", repo_id)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def main():
|
| 129 |
+
start = time.time()
|
| 130 |
+
report = {
|
| 131 |
+
"run_tag": RUN_TAG,
|
| 132 |
+
"approach": "phase3a_drift_inversion_transfer_to_phi4",
|
| 133 |
+
"model_id": MODEL_ID,
|
| 134 |
+
"intervention": "force o_proj layers at 3-bit to 4-bit",
|
| 135 |
+
"eval_protocol": "wikitext-2-raw-v1/test, full set, ctx=2048, stride=2048",
|
| 136 |
+
}
|
| 137 |
+
try:
|
| 138 |
+
cfg = HSAQConfig(
|
| 139 |
+
model_id=MODEL_ID,
|
| 140 |
+
output_dir=str(OUT.parent),
|
| 141 |
+
hf_token=HF_TOKEN,
|
| 142 |
+
gpu_budget_gb=11.2,
|
| 143 |
+
enable_2bit=False,
|
| 144 |
+
enable_pruning=False,
|
| 145 |
+
train_lora=False,
|
| 146 |
+
calibration_samples=128,
|
| 147 |
+
)
|
| 148 |
+
pipe = HSAQPipeline(cfg)
|
| 149 |
+
logger.info("Stage 1: load + profile phi-4")
|
| 150 |
+
model, tokenizer = pipe._load_model()
|
| 151 |
+
model = model.to("cuda:0")
|
| 152 |
+
if tokenizer.pad_token is None:
|
| 153 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 154 |
+
|
| 155 |
+
sensitivity = pipe.profiler.profile(model)
|
| 156 |
+
candidates = pipe._build_layer_candidates(sensitivity, model)
|
| 157 |
+
from quantization.hsaq.assignment import assign_bit_widths
|
| 158 |
+
weight_budget_gb = pipe._compute_weight_budget()
|
| 159 |
+
baseline_assignment = assign_bit_widths(candidates, weight_budget_gb)
|
| 160 |
+
name_to_bits = {a.component: a.chosen.bits for a in baseline_assignment.assignments}
|
| 161 |
+
|
| 162 |
+
# Identify o_proj layers in 3-bit residue
|
| 163 |
+
o_proj_3bit = sorted([n for n, b in name_to_bits.items() if b == 3 and "o_proj" in n])
|
| 164 |
+
logger.info("o_proj layers at 3-bit in baseline assignment: %d", len(o_proj_3bit))
|
| 165 |
+
for n in o_proj_3bit:
|
| 166 |
+
logger.info(" %s", n)
|
| 167 |
+
report["o_proj_3bit_count"] = len(o_proj_3bit)
|
| 168 |
+
report["o_proj_3bit_layers"] = o_proj_3bit
|
| 169 |
+
|
| 170 |
+
# Three-bit residue summary
|
| 171 |
+
residue = sorted([n for n, b in name_to_bits.items() if b == 3])
|
| 172 |
+
report["full_3bit_residue_count"] = len(residue)
|
| 173 |
+
report["full_3bit_residue"] = residue
|
| 174 |
+
|
| 175 |
+
if not o_proj_3bit:
|
| 176 |
+
logger.info("No o_proj at 3-bit — transfer test not applicable on phi-4")
|
| 177 |
+
report["status"] = "transfer_not_applicable"
|
| 178 |
+
report["reason"] = "No o_proj layers landed at 3-bit in baseline assignment"
|
| 179 |
+
# Still do a single baseline eval for the record
|
| 180 |
+
n_hqq = pipe._apply_per_module_hqq(model, name_to_bits, device="cuda:0")
|
| 181 |
+
logger.info("HQQ applied to %d Linears", n_hqq)
|
| 182 |
+
ppl, n_w, pw = evaluate_ppl(model, tokenizer)
|
| 183 |
+
report["ppl_baseline_no_floor"] = ppl
|
| 184 |
+
report["n_windows"] = n_w
|
| 185 |
+
return
|
| 186 |
+
|
| 187 |
+
# Save bf16 weights for the o_proj layers we'll re-quantize twice
|
| 188 |
+
o_proj_bf16, o_proj_bias, o_proj_shape = {}, {}, {}
|
| 189 |
+
for name in o_proj_3bit:
|
| 190 |
+
mod = model.get_submodule(name)
|
| 191 |
+
o_proj_bf16[name] = mod.weight.detach().clone().cpu()
|
| 192 |
+
o_proj_bias[name] = None if mod.bias is None else mod.bias.detach().clone().cpu()
|
| 193 |
+
o_proj_shape[name] = (mod.in_features, mod.out_features)
|
| 194 |
+
|
| 195 |
+
# Apply HQQ to all non-target layers
|
| 196 |
+
non_target_bits = {n: b for n, b in name_to_bits.items() if n not in o_proj_3bit}
|
| 197 |
+
n_hqq = pipe._apply_per_module_hqq(model, non_target_bits, device="cuda:0")
|
| 198 |
+
logger.info("HQQ applied to %d non-target Linears", n_hqq)
|
| 199 |
+
|
| 200 |
+
# Pass 1 — baseline: target o_proj layers HQQ at 3-bit
|
| 201 |
+
logger.info("=== PASS 1: baseline (o_proj at 3-bit) ===")
|
| 202 |
+
for name in o_proj_3bit:
|
| 203 |
+
apply_hqq_one(model, name, nbits=3)
|
| 204 |
+
ppl_baseline, n_w, pw_baseline = evaluate_ppl(model, tokenizer)
|
| 205 |
+
logger.info("Pass 1 PPL: %.4f", ppl_baseline)
|
| 206 |
+
|
| 207 |
+
# Pass 2 — floor: reinstall bf16 on o_proj layers, HQQ at 4-bit
|
| 208 |
+
logger.info("=== PASS 2: floor (o_proj at 4-bit) ===")
|
| 209 |
+
for name in o_proj_3bit:
|
| 210 |
+
in_f, out_f = o_proj_shape[name]
|
| 211 |
+
reinstall_bf16(model, name, o_proj_bf16[name], o_proj_bias[name], in_f, out_f)
|
| 212 |
+
apply_hqq_one(model, name, nbits=4)
|
| 213 |
+
ppl_floor, _, pw_floor = evaluate_ppl(model, tokenizer)
|
| 214 |
+
logger.info("Pass 2 PPL: %.4f", ppl_floor)
|
| 215 |
+
|
| 216 |
+
delta_abs = ppl_baseline - ppl_floor
|
| 217 |
+
delta_pct = (ppl_baseline - ppl_floor) / ppl_baseline * 100
|
| 218 |
+
report["result"] = {
|
| 219 |
+
"ppl_baseline": ppl_baseline,
|
| 220 |
+
"ppl_floor": ppl_floor,
|
| 221 |
+
"delta_abs": delta_abs,
|
| 222 |
+
"delta_pct": delta_pct,
|
| 223 |
+
"n_windows": n_w,
|
| 224 |
+
"per_window_baseline": pw_baseline,
|
| 225 |
+
"per_window_floor": pw_floor,
|
| 226 |
+
}
|
| 227 |
+
report["status"] = "success"
|
| 228 |
+
logger.info("=" * 60)
|
| 229 |
+
logger.info("QWEN-2.5-14B DRIFT-INVERSION TRANSFER:")
|
| 230 |
+
logger.info(" baseline (o_proj@3): %.4f", ppl_baseline)
|
| 231 |
+
logger.info(" floor (o_proj@4): %.4f", ppl_floor)
|
| 232 |
+
logger.info(" delta: %.4f (%+.3f%%) %s", delta_abs, -delta_pct,
|
| 233 |
+
"← drift-inversion confirmed" if delta_abs > 0 else "← does not transfer")
|
| 234 |
+
logger.info("=" * 60)
|
| 235 |
+
except Exception as e:
|
| 236 |
+
logger.exception("Run failed")
|
| 237 |
+
report["status"] = "failed"
|
| 238 |
+
report["error"] = repr(e)
|
| 239 |
+
finally:
|
| 240 |
+
report["elapsed_s"] = round(time.time() - start, 1)
|
| 241 |
+
upload_report(report)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
if __name__ == "__main__":
|
| 245 |
+
main()
|