File size: 10,119 Bytes
ac3cd07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
# /// script
# requires-python = ">=3.11"
# dependencies = [
#   "torch>=2.1,<2.7",
#   "transformers>=4.46,<4.50",
#   "datasets",
#   "hqq>=0.2.8",
#   "accelerate",
#   "tqdm",
#   "huggingface_hub",
# ]
# ///
"""
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}

        # Identify o_proj layers in 3-bit residue
        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

        # Three-bit residue summary
        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"
            # Still do a single baseline eval for the record
            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

        # Save bf16 weights for the o_proj layers we'll re-quantize twice
        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)

        # Apply HQQ to all non-target layers
        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)

        # Pass 1 β€” baseline: target o_proj layers HQQ at 3-bit
        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)

        # Pass 2 β€” floor: reinstall bf16 on o_proj layers, HQQ at 4-bit
        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()