mxguru1 commited on
Commit
4e75b89
·
verified ·
1 Parent(s): 48ec8ad

Add compare_strategies.py

Browse files
Files changed (1) hide show
  1. compare_strategies.py +395 -0
compare_strategies.py ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.10"
3
+ # dependencies = [
4
+ # "torch>=2.5,<2.10",
5
+ # "transformers>=4.46",
6
+ # "huggingface_hub>=0.26",
7
+ # "datasets>=3.0",
8
+ # "accelerate>=1.0",
9
+ # "sentencepiece",
10
+ # "protobuf",
11
+ # ]
12
+ # ///
13
+ """
14
+ Strategy A vs Strategy B comparison for HSAQ KV-cache profiling.
15
+
16
+ The kv_profiler.py shipped by web-Claude implements STRATEGY B (per-config
17
+ joint): for each config, hook every layer simultaneously via
18
+ kv_quant_active_multi, run ONE forward pass, capture per-layer attention-output
19
+ drift in one shot. Total cost: 11 forwards.
20
+
21
+ STRATEGY A (per-layer isolated): for each (layer, config) pair, hook ONLY
22
+ that layer via kv_quant_active, run a forward pass, measure drift at the
23
+ target layer. Total cost: 11 × N_layers = 440 forwards for OLMo's 40 layers.
24
+
25
+ This script runs both on OLMo-2-13B-Instruct, diffs the resulting drift
26
+ tables, and pipes each through assign_kv_bits to compare the allocation
27
+ decisions. Outputs a comparison report to
28
+ mxguru1/hsaq-strategy-comparison.
29
+
30
+ If A and B agree: keep B for speed, allocator independence assumption holds.
31
+ If A and B disagree: the disagreement IS the finding, and the allocator
32
+ should consume A's data despite the cost.
33
+ """
34
+ from __future__ import annotations
35
+
36
+ import json
37
+ import os
38
+ import sys
39
+ import time
40
+ from datetime import datetime, timezone
41
+ from pathlib import Path
42
+
43
+ import torch
44
+ from huggingface_hub import HfApi, hf_hub_download, login, snapshot_download, create_repo
45
+
46
+ # ---------------------------------------------------------------------------
47
+ # Auth + setup
48
+ # ---------------------------------------------------------------------------
49
+
50
+ token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
51
+ if not token:
52
+ print("FATAL: no HF_TOKEN in env")
53
+ sys.exit(2)
54
+ login(token=token)
55
+ print("[auth] logged in as mxguru1")
56
+
57
+ # Pull the HSAQ tools from the Hub (so we don't need a local checkout)
58
+ print("[fetch] pulling HSAQ tools from mxguru1/hsaq-tools")
59
+ local_tools = snapshot_download(
60
+ repo_id="mxguru1/hsaq-tools",
61
+ local_dir="/tmp/hsaq_tools",
62
+ allow_patterns=["kv_intercept.py", "kv_profiler.py", "assignment_v2.py"],
63
+ )
64
+ sys.path.insert(0, local_tools)
65
+ print(f"[fetch] tools at {local_tools}")
66
+
67
+ import kv_intercept as kvi
68
+ import kv_profiler as kvp
69
+ import assignment_v2 as asgn
70
+
71
+ # ---------------------------------------------------------------------------
72
+ # Model + calibration
73
+ # ---------------------------------------------------------------------------
74
+
75
+ TARGET_MODEL = "allenai/OLMo-2-1124-13B-Instruct"
76
+ N_CALIB = 32 # calibration set size
77
+ MAX_SEQ_LEN = 512 # truncation length
78
+ KV_BUDGET_GB = 1.0 # for allocator comparison
79
+
80
+ print(f"\n[stage] target model: {TARGET_MODEL}")
81
+ print(f"[stage] calibration: {N_CALIB} prompts, max_seq_len={MAX_SEQ_LEN}")
82
+
83
+ from transformers import AutoModelForCausalLM, AutoTokenizer
84
+ from datasets import load_dataset
85
+
86
+ t0 = time.time()
87
+ tok = AutoTokenizer.from_pretrained(TARGET_MODEL, trust_remote_code=True)
88
+ if tok.pad_token is None:
89
+ tok.pad_token = tok.eos_token
90
+ model = AutoModelForCausalLM.from_pretrained(
91
+ TARGET_MODEL,
92
+ torch_dtype=torch.bfloat16,
93
+ device_map="auto",
94
+ trust_remote_code=True,
95
+ )
96
+ model.eval()
97
+ print(f"[stage] model loaded in {time.time()-t0:.1f}s, VRAM: {torch.cuda.memory_allocated()/1e9:.2f} GB")
98
+
99
+ # Pull calibration prompts from the wargame corpus
100
+ print(f"[stage] loading calibration from mxguru1/master-chief-wargame-corpus-v1")
101
+ ds = load_dataset("mxguru1/master-chief-wargame-corpus-v1", split="train")
102
+ calibration_texts = [row["attack"] for row in ds.select(range(N_CALIB))]
103
+ print(f"[stage] {len(calibration_texts)} calibration prompts ready")
104
+
105
+ # ---------------------------------------------------------------------------
106
+ # Strategy B — already implemented in kv_profiler.profile_kv_sensitivity
107
+ # ---------------------------------------------------------------------------
108
+
109
+ print("\n" + "=" * 72)
110
+ print("STRATEGY B (per-config JOINT — current default, 11 forwards)")
111
+ print("=" * 72)
112
+ t0 = time.time()
113
+ rows_B = kvp.profile_kv_sensitivity(
114
+ model=model,
115
+ tokenizer=tok,
116
+ calibration_texts=calibration_texts,
117
+ model_hash="olmo-2-13b-strategy-B",
118
+ profiled_by_agent_id="strategy-compare",
119
+ profiled_by_agent_tier=1,
120
+ max_seq_len=MAX_SEQ_LEN,
121
+ drift_metric="mse_normalised",
122
+ progress_cb=lambda m: print(f" {m}"),
123
+ )
124
+ elapsed_B = time.time() - t0
125
+ print(f"[B] {len(rows_B)} rows in {elapsed_B:.1f}s")
126
+
127
+ # ---------------------------------------------------------------------------
128
+ # Strategy A — per (layer, config) isolated, hook ONE layer at a time
129
+ # ---------------------------------------------------------------------------
130
+
131
+
132
+ def profile_isolated(
133
+ model, tokenizer, calibration_texts, model_hash, max_seq_len, sweep,
134
+ ):
135
+ """Strategy A: hook one layer at a time, measure drift at that layer.
136
+
137
+ For each config, for each layer:
138
+ - install hook on ONLY this layer at this config
139
+ - run forward, capture all layer attention outputs (cheap)
140
+ - record drift at the target layer
141
+ """
142
+ from kv_intercept import KVQuantSpec, find_attention_modules, kv_quant_active
143
+
144
+ rows = []
145
+ attn_modules = find_attention_modules(model)
146
+ n_layers = len(attn_modules)
147
+
148
+ # Tokenize once
149
+ batch = tokenizer(
150
+ calibration_texts,
151
+ return_tensors="pt",
152
+ padding=True,
153
+ truncation=True,
154
+ max_length=max_seq_len,
155
+ ).to(model.device)
156
+ actual_seq_len = batch.input_ids.shape[1]
157
+
158
+ # Capture full-precision baseline (one forward)
159
+ print(f" [A] capturing fp baseline ({n_layers} layers, 1 forward)")
160
+ t_b = time.time()
161
+ baseline_outputs = kvp._capture_attn_outputs(model, attn_modules, batch)
162
+ print(f" [A] baseline in {time.time()-t_b:.1f}s")
163
+
164
+ # Per-layer dimensions (Llama-family assumption)
165
+ cfg = model.config
166
+ num_kv_heads = getattr(cfg, "num_key_value_heads",
167
+ getattr(cfg, "num_attention_heads", 1))
168
+ head_dim = getattr(cfg, "head_dim", None) or (
169
+ cfg.hidden_size // cfg.num_attention_heads
170
+ )
171
+
172
+ calibration_hash = kvp.compute_calibration_hash(calibration_texts, max_seq_len)
173
+ profiled_at = datetime.now(timezone.utc).isoformat()
174
+
175
+ total_forwards = len(sweep) * n_layers
176
+ forward_idx = 0
177
+ t_loop = time.time()
178
+
179
+ for cfg_idx, swp in enumerate(sweep):
180
+ spec = KVQuantSpec(
181
+ k_bits=swp.k_bits,
182
+ v_bits=swp.v_bits,
183
+ quantizer=swp.quantizer,
184
+ group_size=swp.group_size,
185
+ )
186
+ bpt = kvp.kv_bytes_per_token(
187
+ num_kv_heads=num_kv_heads,
188
+ head_dim=head_dim,
189
+ k_bits=swp.k_bits,
190
+ v_bits=swp.v_bits,
191
+ quantizer=swp.quantizer,
192
+ group_size=swp.group_size,
193
+ )
194
+
195
+ for layer_idx, attn in attn_modules.items():
196
+ forward_idx += 1
197
+ if forward_idx % 40 == 0:
198
+ elapsed = time.time() - t_loop
199
+ eta = elapsed / forward_idx * (total_forwards - forward_idx)
200
+ print(f" [A] forward {forward_idx}/{total_forwards} "
201
+ f"(cfg {cfg_idx+1}/{len(sweep)} k={swp.k_bits} v={swp.v_bits} "
202
+ f"{swp.quantizer}, eta {eta:.0f}s)")
203
+
204
+ # Hook ONLY this layer at this config
205
+ with kv_quant_active(attn, spec):
206
+ captured = kvp._capture_attn_outputs(model, attn_modules, batch)
207
+
208
+ if layer_idx not in captured or layer_idx not in baseline_outputs:
209
+ continue
210
+
211
+ drift = kvp.compute_drift(
212
+ captured[layer_idx],
213
+ baseline_outputs[layer_idx],
214
+ "mse_normalised",
215
+ )
216
+
217
+ rows.append(kvp.ProfileRow(
218
+ model_hash=model_hash,
219
+ calibration_hash=calibration_hash,
220
+ pipeline_version="strategy-A-1.0.0",
221
+ layer_idx=layer_idx,
222
+ k_bits=swp.k_bits,
223
+ v_bits=swp.v_bits,
224
+ quantizer=swp.quantizer,
225
+ drift_attn_output=float(drift),
226
+ drift_metric="mse_normalised",
227
+ bytes_per_kv_token=float(bpt),
228
+ max_seq_len_observed=actual_seq_len,
229
+ num_kv_heads=num_kv_heads,
230
+ head_dim=head_dim,
231
+ profiled_at=profiled_at,
232
+ profiled_by_agent_id="strategy-compare",
233
+ profiled_by_agent_tier=1,
234
+ ))
235
+
236
+ return rows
237
+
238
+
239
+ print("\n" + "=" * 72)
240
+ print("STRATEGY A (per-layer ISOLATED — 11 × N_layers forwards)")
241
+ print("=" * 72)
242
+ t0 = time.time()
243
+ rows_A = profile_isolated(
244
+ model, tok, calibration_texts,
245
+ model_hash="olmo-2-13b-strategy-A",
246
+ max_seq_len=MAX_SEQ_LEN,
247
+ sweep=kvp.DEFAULT_SWEEP,
248
+ )
249
+ elapsed_A = time.time() - t0
250
+ print(f"[A] {len(rows_A)} rows in {elapsed_A:.1f}s")
251
+
252
+ # ---------------------------------------------------------------------------
253
+ # Diff the drift tables
254
+ # ---------------------------------------------------------------------------
255
+
256
+ print("\n" + "=" * 72)
257
+ print("COMPARISON")
258
+ print("=" * 72)
259
+ print(f"\n Strategy B: {elapsed_B:.1f}s wall, {len(rows_B)} rows")
260
+ print(f" Strategy A: {elapsed_A:.1f}s wall, {len(rows_A)} rows")
261
+ print(f" Ratio A/B: {elapsed_A/max(elapsed_B,0.1):.1f}× slower")
262
+
263
+ # Build (config, layer) -> drift maps
264
+ def key_drift(rows):
265
+ return {(r.k_bits, r.v_bits, r.quantizer, r.layer_idx): r.drift_attn_output
266
+ for r in rows}
267
+
268
+ B_map = key_drift(rows_B)
269
+ A_map = key_drift(rows_A)
270
+ common = set(B_map.keys()) & set(A_map.keys())
271
+ print(f"\n Common (config, layer) pairs: {len(common)}")
272
+
273
+ # Aggregate by config — drift averaged over layers
274
+ def avg_by_config(d):
275
+ from collections import defaultdict
276
+ by_cfg = defaultdict(list)
277
+ for (k, v, q, _li), drift in d.items():
278
+ by_cfg[(k, v, q)].append(drift)
279
+ return {cfg: sum(vs) / len(vs) for cfg, vs in by_cfg.items()}
280
+
281
+ avg_B = avg_by_config(B_map)
282
+ avg_A = avg_by_config(A_map)
283
+ all_cfgs = sorted(set(avg_B) | set(avg_A))
284
+
285
+ print(f"\n Per-config average drift (lower = quant is less harmful):")
286
+ print(f" {'config':<36} {'A_isolated':>13} {'B_joint':>13} {'A/B ratio':>10}")
287
+ for cfg in all_cfgs:
288
+ a = avg_A.get(cfg, 0)
289
+ b = avg_B.get(cfg, 0)
290
+ ratio = a / max(b, 1e-12)
291
+ print(f" {str(cfg):<36} {a:>13.4e} {b:>13.4e} {ratio:>10.2f}")
292
+
293
+ # Allocator comparison
294
+ print(f"\n Running allocator on each (KV budget = {KV_BUDGET_GB} GB, max_seq_len={MAX_SEQ_LEN})")
295
+ cands_B = kvp.rows_to_kv_candidates(rows_B)
296
+ cands_A = kvp.rows_to_kv_candidates(rows_A)
297
+ try:
298
+ res_B = asgn.assign_kv_bits(cands_B, kv_budget_gb=KV_BUDGET_GB, max_seq_len=MAX_SEQ_LEN)
299
+ res_A = asgn.assign_kv_bits(cands_A, kv_budget_gb=KV_BUDGET_GB, max_seq_len=MAX_SEQ_LEN)
300
+ except Exception as e:
301
+ print(f" allocator err: {e}")
302
+ res_B = res_A = None
303
+
304
+ if res_A and res_B:
305
+ from collections import Counter
306
+ pick_B = Counter((a.chosen.k_bits, a.chosen.v_bits, a.chosen.quantizer)
307
+ for a in res_B.assignments)
308
+ pick_A = Counter((a.chosen.k_bits, a.chosen.v_bits, a.chosen.quantizer)
309
+ for a in res_A.assignments)
310
+ print(f"\n Allocation distribution (B vs A):")
311
+ all_picks = sorted(set(pick_B) | set(pick_A))
312
+ for p in all_picks:
313
+ print(f" {str(p):<40} B={pick_B[p]:>3} A={pick_A[p]:>3}")
314
+ print(f"\n Total drift B={res_B.total_drift:.4e} A={res_A.total_drift:.4e}")
315
+ print(f" Total KV GB B={res_B.total_kv_gb:.3f} A={res_A.total_kv_gb:.3f}")
316
+
317
+ # Layer-by-layer agreement
318
+ agree_count = sum(
319
+ 1 for la, lb in zip(res_A.assignments, res_B.assignments)
320
+ if (la.chosen.k_bits, la.chosen.v_bits, la.chosen.quantizer) ==
321
+ (lb.chosen.k_bits, lb.chosen.v_bits, lb.chosen.quantizer)
322
+ )
323
+ print(f"\n Per-layer agreement: {agree_count}/{len(res_A.assignments)}")
324
+
325
+ # ---------------------------------------------------------------------------
326
+ # Persist to HF Hub
327
+ # ---------------------------------------------------------------------------
328
+
329
+ out_repo = "mxguru1/hsaq-strategy-comparison"
330
+ try:
331
+ create_repo(out_repo, repo_type="dataset", exist_ok=True, private=False)
332
+ except Exception:
333
+ pass
334
+
335
+ report = {
336
+ "captured_at": datetime.now(timezone.utc).isoformat(),
337
+ "target_model": TARGET_MODEL,
338
+ "calibration": {
339
+ "source": "mxguru1/master-chief-wargame-corpus-v1",
340
+ "n_prompts": N_CALIB,
341
+ "max_seq_len": MAX_SEQ_LEN,
342
+ },
343
+ "strategy_B": {
344
+ "elapsed_seconds": round(elapsed_B, 1),
345
+ "n_rows": len(rows_B),
346
+ "n_forwards": 11,
347
+ "avg_drift_by_config": {str(k): v for k, v in avg_B.items()},
348
+ },
349
+ "strategy_A": {
350
+ "elapsed_seconds": round(elapsed_A, 1),
351
+ "n_rows": len(rows_A),
352
+ "n_forwards": 11 * 40,
353
+ "avg_drift_by_config": {str(k): v for k, v in avg_A.items()},
354
+ },
355
+ "ratio_a_over_b": round(elapsed_A / max(elapsed_B, 0.1), 2),
356
+ "allocator_kv_budget_gb": KV_BUDGET_GB,
357
+ }
358
+ if res_A and res_B:
359
+ report["allocator_comparison"] = {
360
+ "agreement_per_layer": f"{agree_count}/{len(res_A.assignments)}",
361
+ "total_drift_A": res_A.total_drift,
362
+ "total_drift_B": res_B.total_drift,
363
+ "total_kv_gb_A": res_A.total_kv_gb,
364
+ "total_kv_gb_B": res_B.total_kv_gb,
365
+ }
366
+
367
+ api = HfApi()
368
+ report_path = "/tmp/comparison_report.json"
369
+ with open(report_path, "w") as f:
370
+ json.dump(report, f, indent=2)
371
+
372
+ api.upload_file(
373
+ path_or_fileobj=report_path,
374
+ path_in_repo="report.json",
375
+ repo_id=out_repo,
376
+ repo_type="dataset",
377
+ commit_message=f"Strategy A vs B on {TARGET_MODEL}",
378
+ )
379
+
380
+ # Also dump raw rows for follow-up analysis
381
+ rows_dump = {
382
+ "strategy_A": [r.to_vault_payload() for r in rows_A],
383
+ "strategy_B": [r.to_vault_payload() for r in rows_B],
384
+ }
385
+ rows_path = "/tmp/comparison_rows.json"
386
+ with open(rows_path, "w") as f:
387
+ json.dump(rows_dump, f, indent=2)
388
+ api.upload_file(
389
+ path_or_fileobj=rows_path,
390
+ path_in_repo="rows.json",
391
+ repo_id=out_repo,
392
+ repo_type="dataset",
393
+ commit_message="Raw profile rows for follow-up analysis",
394
+ )
395
+ print(f"\n[done] report + rows pushed to https://huggingface.co/datasets/{out_repo}")