MarxistLeninist commited on
Commit
2fe0468
·
verified ·
1 Parent(s): 139c83b

Upload qsched_repro.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. qsched_repro.py +357 -0
qsched_repro.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.10"
3
+ # dependencies = [
4
+ # "torch",
5
+ # "diffusers>=0.27",
6
+ # "transformers>=4.38",
7
+ # "accelerate",
8
+ # "pillow",
9
+ # "numpy",
10
+ # ]
11
+ # ///
12
+ """
13
+ Independent toy-scale reproduction of Q-Sched (arXiv 2509.01624).
14
+
15
+ Core mechanism under test: a quantized few-step diffusion model can recover
16
+ quality by re-optimising two scalar scheduler preconditioning coefficients
17
+ (c_x on the latent term, c_eps on the prediction term), selected by the
18
+ reference-free JAQ loss (CLIPScore + CLIP-IQA-Q). Weights stay fixed.
19
+
20
+ Runs on a real SD1.5 4-step LCM pipeline (GPU) or on a deterministic mock
21
+ pipeline (`--smoke`, CPU) that exercises every code path without a download.
22
+ """
23
+ import argparse, json, os, hashlib, math, time
24
+ import numpy as np
25
+
26
+ def log(*a):
27
+ print("[qsched]", *a, flush=True)
28
+
29
+ # ----------------------------- fake quantization -----------------------------
30
+ def fake_quant_(tensor, bits):
31
+ """Per-tensor symmetric fake-quant, in place-returning a new tensor."""
32
+ import torch
33
+ qmax = 2 ** (bits - 1) - 1
34
+ s = tensor.abs().max() / qmax
35
+ if float(s) == 0.0:
36
+ return tensor.clone()
37
+ q = torch.clamp(torch.round(tensor / s), -qmax - 1, qmax)
38
+ return q * s
39
+
40
+ def apply_weight_quant(unet, bits):
41
+ """Fake-quantize Conv2d/Linear weights. Returns dict of originals for restore."""
42
+ import torch, torch.nn as nn
43
+ originals = {}
44
+ for name, m in unet.named_modules():
45
+ if isinstance(m, (nn.Conv2d, nn.Linear)) and hasattr(m, "weight") and m.weight is not None:
46
+ originals[name] = m.weight.data.clone()
47
+ m.weight.data = fake_quant_(m.weight.data, bits)
48
+ return originals
49
+
50
+ def restore_weights(unet, originals):
51
+ for name, m in unet.named_modules():
52
+ if name in originals:
53
+ m.weight.data = originals[name].clone()
54
+
55
+ def unet_weight_hash(unet):
56
+ import torch
57
+ h = hashlib.sha256()
58
+ for name, p in sorted(unet.named_parameters()):
59
+ h.update(name.encode())
60
+ h.update(p.data.detach().to("cpu", torch.float32).numpy().tobytes())
61
+ return h.hexdigest()
62
+
63
+ # --------------------------- Q-Sched LCM scheduler ---------------------------
64
+ # Faithful LCM consistency step with two Q-Sched coefficients.
65
+ # denoised = c_x * (c_skip * x_t) + c_eps * (c_out * pred_x0)
66
+ # (c_x, c_eps) = (1, 1) reproduces the stock LCM update.
67
+ class QSchedLCM:
68
+ def __init__(self, alphas_cumprod, timestep_scaling=10.0, sigma_data=0.5):
69
+ import torch
70
+ self.acp = alphas_cumprod # tensor [T]
71
+ self.timestep_scaling = timestep_scaling
72
+ self.sigma_data = sigma_data
73
+
74
+ def cskip_cout(self, t):
75
+ st = t * self.timestep_scaling
76
+ c_skip = self.sigma_data ** 2 / (st ** 2 + self.sigma_data ** 2)
77
+ c_out = st / math.sqrt(st ** 2 + self.sigma_data ** 2)
78
+ return c_skip, c_out
79
+
80
+ def step(self, model_output, t, t_prev, sample, noise, c_x=1.0, c_eps=1.0, last=False):
81
+ import torch
82
+ acp_t = self.acp[t]
83
+ alpha_t = acp_t.sqrt(); sigma_t = (1 - acp_t).sqrt()
84
+ pred_x0 = (sample - sigma_t * model_output) / alpha_t
85
+ c_skip, c_out = self.cskip_cout(int(t))
86
+ denoised = c_x * (c_skip * sample) + c_eps * (c_out * pred_x0)
87
+ if last:
88
+ return denoised
89
+ acp_p = self.acp[t_prev]
90
+ alpha_p = acp_p.sqrt(); sigma_p = (1 - acp_p).sqrt()
91
+ return alpha_p * denoised + sigma_p * noise
92
+
93
+ # ------------------------------- JAQ loss -----------------------------------
94
+ class JAQ:
95
+ """Reference-free: CLIPScore (text-image) + CLIP-IQA-Q (antonym quality)."""
96
+ def __init__(self, device, mock=False):
97
+ self.mock = mock; self.device = device
98
+ if mock:
99
+ return
100
+ import torch
101
+ from transformers import CLIPModel, CLIPProcessor
102
+ self.model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32").to(device).eval()
103
+ self.proc = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
104
+ # CLIP-IQA-Q antonym prompt pair
105
+ self.iqa_pos, self.iqa_neg = "Good photo.", "Bad photo."
106
+
107
+ def _img_emb(self, pil):
108
+ import torch
109
+ px = self.proc(images=pil, return_tensors="pt").to(self.device)
110
+ with torch.no_grad():
111
+ e = self.model.get_image_features(**px)
112
+ return e / e.norm(dim=-1, keepdim=True)
113
+
114
+ def _txt_emb(self, texts):
115
+ import torch
116
+ tk = self.proc(text=texts, return_tensors="pt", padding=True).to(self.device)
117
+ with torch.no_grad():
118
+ e = self.model.get_text_features(**tk)
119
+ return e / e.norm(dim=-1, keepdim=True)
120
+
121
+ def score(self, pil, prompt):
122
+ """Return (clipscore, clipiqa_q, jaq)."""
123
+ if self.mock:
124
+ # deterministic mock quality from image mean (exercises the pipeline)
125
+ arr = np.asarray(pil).astype(np.float32) / 255.0
126
+ cs = float(arr.mean()); iqa = float(1.0 - arr.std())
127
+ return cs, iqa, cs + iqa
128
+ import torch
129
+ ie = self._img_emb(pil)
130
+ te = self._txt_emb([prompt])
131
+ clipscore = float((ie @ te.T).item())
132
+ pair = self._txt_emb([self.iqa_pos, self.iqa_neg])
133
+ sims = (ie @ pair.T).squeeze(0) * 100.0
134
+ iqa_q = float(torch.softmax(sims, dim=0)[0].item())
135
+ return clipscore, iqa_q, clipscore + iqa_q
136
+
137
+ # ----------------------------- pipeline wrappers -----------------------------
138
+ class MockPipe:
139
+ """CPU mock: tiny UNet-like function + fake VAE, deterministic. No download."""
140
+ def __init__(self, device):
141
+ import torch, torch.nn as nn
142
+ torch.manual_seed(0)
143
+ self.device = device
144
+ T = 1000
145
+ self.acp = torch.linspace(0.9999, 0.02, T) # decreasing alpha_cumprod
146
+ self.unet = nn.Sequential(nn.Conv2d(4, 8, 3, padding=1), nn.SiLU(),
147
+ nn.Conv2d(8, 4, 3, padding=1)).to(device)
148
+ self.qsched = QSchedLCM(self.acp)
149
+
150
+ def eps(self, x, t):
151
+ import torch
152
+ return self.unet(x)
153
+
154
+ def generate(self, prompt, seed, steps, c_x, c_eps, bits_originals=None):
155
+ import torch
156
+ g = torch.Generator(device="cpu").manual_seed(seed + hash(prompt) % 1000)
157
+ x = torch.randn(1, 4, 16, 16, generator=g).to(self.device)
158
+ ts = torch.linspace(999, 0, steps + 1).long()
159
+ for i in range(steps):
160
+ t, tp = int(ts[i]), int(ts[i + 1])
161
+ mo = self.eps(x, t)
162
+ noise = torch.randn(x.shape, generator=g).to(self.device)
163
+ x = self.qsched.step(mo, t, tp, x, noise, c_x, c_eps, last=(i == steps - 1))
164
+ # fake decode -> [0,255] image
165
+ img = ((x[0].mean(0).clamp(-2, 2) + 2) / 4 * 255).to(torch.uint8).cpu().numpy()
166
+ from PIL import Image
167
+ return Image.fromarray(np.stack([img] * 3, -1))
168
+
169
+ class RealPipe:
170
+ """SD1.5 4-step LCM via diffusers, with QSched sampler override."""
171
+ def __init__(self, model_id, device, dtype):
172
+ import torch
173
+ from diffusers import LatentConsistencyModelPipeline
174
+ self.device = device; self.dtype = dtype
175
+ self.pipe = LatentConsistencyModelPipeline.from_pretrained(model_id, torch_dtype=dtype, safety_checker=None)
176
+ self.pipe.to(device)
177
+ self.unet = self.pipe.unet
178
+ acp = self.pipe.scheduler.alphas_cumprod.to(device=device, dtype=torch.float32)
179
+ self.acp = acp
180
+ self.qsched = QSchedLCM(acp)
181
+
182
+ def generate(self, prompt, seed, steps, c_x, c_eps):
183
+ import torch
184
+ pipe = self.pipe
185
+ g = torch.Generator(device=self.device).manual_seed(seed)
186
+ # encode prompt
187
+ pe, _ = pipe.encode_prompt(prompt, self.device, 1, False)
188
+ pipe.scheduler.set_timesteps(steps, device=self.device)
189
+ timesteps = pipe.scheduler.timesteps
190
+ # initial latent
191
+ num_ch = pipe.unet.config.in_channels
192
+ h = w = 512 // pipe.vae_scale_factor
193
+ lat = torch.randn((1, num_ch, h, w), generator=g, device=self.device, dtype=self.dtype)
194
+ lat = lat * pipe.scheduler.init_noise_sigma
195
+ n = len(timesteps)
196
+ for i, t in enumerate(timesteps):
197
+ mo = pipe.unet(lat, t, encoder_hidden_states=pe, return_dict=False)[0]
198
+ tp = int(timesteps[i + 1]) if i + 1 < n else 0
199
+ noise = torch.randn(lat.shape, generator=g, device=self.device, dtype=self.dtype)
200
+ lat = self.qsched.step(mo.float(), int(t), tp, lat.float(), noise.float(),
201
+ c_x, c_eps, last=(i == n - 1)).to(self.dtype)
202
+ img = pipe.vae.decode(lat / pipe.vae.config.scaling_factor, return_dict=False)[0]
203
+ img = pipe.image_processor.postprocess(img, output_type="pil")[0]
204
+ return img
205
+
206
+ # --------------------------------- driver -----------------------------------
207
+ CALIB_PROMPTS = [
208
+ "a photograph of an astronaut riding a horse",
209
+ "a bowl of fresh strawberries on a wooden table",
210
+ "a red sports car on a mountain road at sunset",
211
+ "a cozy cabin in a snowy forest, warm light",
212
+ "a portrait of a woman with curly hair, studio lighting",
213
+ "a bustling city street market at night",
214
+ ]
215
+ EVAL_PROMPTS = [
216
+ "a golden retriever puppy playing in a garden",
217
+ "a lighthouse on a rocky coast under storm clouds",
218
+ "a plate of sushi with chopsticks, top view",
219
+ "an old library with tall bookshelves and a ladder",
220
+ "a hot air balloon over a green valley",
221
+ "a steaming cup of coffee on a rainy window sill",
222
+ "a majestic eagle soaring over mountains",
223
+ "a futuristic city skyline with flying cars",
224
+ "a field of sunflowers under a blue sky",
225
+ "a vintage bicycle leaning against a brick wall",
226
+ "a bengal tiger walking through tall grass",
227
+ "a wooden sailboat on a calm lake at dawn",
228
+ ]
229
+
230
+ def mean(xs): return float(sum(xs) / len(xs)) if xs else 0.0
231
+
232
+ def eval_config(pipe, jaq, prompts, seed, steps, c_x, c_eps, save_dir=None, tag=None):
233
+ cs, iqa, jq = [], [], []
234
+ for i, p in enumerate(prompts):
235
+ img = pipe.generate(p, seed, steps, c_x, c_eps)
236
+ a, b, c = jaq.score(img, p)
237
+ cs.append(a); iqa.append(b); jq.append(c)
238
+ if save_dir is not None and i < 3:
239
+ try:
240
+ img.save(os.path.join(save_dir, f"{tag}_p{i}.png"))
241
+ except Exception as e:
242
+ log("img save failed", e)
243
+ return {"clipscore": mean(cs), "clipiqa_q": mean(iqa), "jaq": mean(jq)}
244
+
245
+ def grid_search(pipe, jaq, prompts, seed, steps, grid):
246
+ results = []
247
+ for cx in grid:
248
+ for ce in grid:
249
+ r = eval_config(pipe, jaq, prompts, seed, steps, cx, ce)
250
+ r["c_x"], r["c_eps"] = cx, ce
251
+ results.append(r)
252
+ log(f" grid c_x={cx:.2f} c_eps={ce:.2f} JAQ={r['jaq']:.4f}")
253
+ best = max(results, key=lambda r: r["jaq"])
254
+ return best, results
255
+
256
+ def main():
257
+ ap = argparse.ArgumentParser()
258
+ ap.add_argument("--smoke", action="store_true")
259
+ ap.add_argument("--model", default="SimianLuo/LCM_Dreamshaper_v7")
260
+ ap.add_argument("--steps", type=int, default=4)
261
+ ap.add_argument("--seed", type=int, default=1234)
262
+ ap.add_argument("--bits", type=int, nargs="+", default=[8, 4])
263
+ ap.add_argument("--grid", type=float, nargs="+",
264
+ default=[0.90, 0.95, 1.00, 1.05, 1.10])
265
+ ap.add_argument("--n-calib", type=int, default=6)
266
+ ap.add_argument("--n-eval", type=int, default=12)
267
+ ap.add_argument("--out", default="outputs/results.json")
268
+ args = ap.parse_args()
269
+
270
+ import torch
271
+ device = "cuda" if (not args.smoke and torch.cuda.is_available()) else "cpu"
272
+ dtype = torch.float16 if device == "cuda" else torch.float32
273
+ log(f"device={device} smoke={args.smoke} steps={args.steps} bits={args.bits} grid={args.grid}")
274
+
275
+ if args.smoke:
276
+ pipe = MockPipe(device)
277
+ else:
278
+ pipe = RealPipe(args.model, device, dtype)
279
+ jaq = JAQ(device, mock=args.smoke)
280
+
281
+ calib = CALIB_PROMPTS[:args.n_calib]
282
+ ev = EVAL_PROMPTS[:args.n_eval]
283
+ unet = pipe.unet
284
+
285
+ out = {"meta": {"paper": "Q-Sched arXiv:2509.01624", "model": args.model,
286
+ "device": device, "steps": args.steps, "grid": args.grid,
287
+ "smoke": args.smoke, "seed": args.seed,
288
+ "n_calib": len(calib), "n_eval": len(ev)},
289
+ "bitwidths": {}}
290
+
291
+ save_dir = os.path.dirname(args.out) or "."
292
+ os.makedirs(save_dir, exist_ok=True)
293
+ # ---- FP16 reference (Claim 1 hash before) ----
294
+ hash_before = unet_weight_hash(unet)
295
+ t0 = time.time()
296
+ fp16 = eval_config(pipe, jaq, ev, args.seed, args.steps, 1.0, 1.0, save_dir, "fp16")
297
+ log(f"FP16 eval: {fp16}")
298
+ out["fp16_reference"] = fp16
299
+ out["weight_hash_fp16"] = hash_before
300
+
301
+ rng = np.random.RandomState(0)
302
+ for bits in args.bits:
303
+ log(f"=== W{bits} ===")
304
+ originals = apply_weight_quant(unet, bits)
305
+ hash_quant = unet_weight_hash(unet)
306
+ # default sampler baseline
307
+ base = eval_config(pipe, jaq, ev, args.seed, args.steps, 1.0, 1.0, save_dir, f"w{bits}_default")
308
+ log(f"W{bits} quant + default(1,1) eval: {base}")
309
+ # grid search on calibration prompts (reference-free)
310
+ best, grid_all = grid_search(pipe, jaq, calib, args.seed, args.steps, args.grid)
311
+ log(f"W{bits} JAQ-selected c_x={best['c_x']} c_eps={best['c_eps']}")
312
+ qsched = eval_config(pipe, jaq, ev, args.seed, args.steps, best["c_x"], best["c_eps"], save_dir, f"w{bits}_qsched")
313
+ log(f"W{bits} quant + Q-Sched eval: {qsched}")
314
+ # negative control: random coeff pair (not (1,1), not the selected best)
315
+ rc, tries = None, 0
316
+ while tries < 200:
317
+ tries += 1
318
+ cand = (round(float(rng.choice(args.grid)), 2), round(float(rng.choice(args.grid)), 2))
319
+ if cand != (best["c_x"], best["c_eps"]) and cand != (1.0, 1.0):
320
+ rc = cand; break
321
+ if rc is None: # degenerate grid (e.g. single point) — skip control
322
+ rand = None
323
+ log(f"W{bits} random control skipped (grid too small)")
324
+ else:
325
+ rand = eval_config(pipe, jaq, ev, args.seed, args.steps, rc[0], rc[1])
326
+ log(f"W{bits} quant + random{rc} eval: {rand}")
327
+ # Claim-1 check: weights identical before/after Q-Sched sampler run
328
+ hash_after = unet_weight_hash(unet)
329
+ restore_weights(unet, originals)
330
+ out["bitwidths"][f"W{bits}"] = {
331
+ "quant_default": base, "qsched": qsched, "random_control": rand,
332
+ "selected_c_x": best["c_x"], "selected_c_eps": best["c_eps"],
333
+ "random_coeff": rc, "grid": grid_all,
334
+ "weight_hash_quant": hash_quant,
335
+ "weight_hash_after_qsched": hash_after,
336
+ "weights_unchanged_by_sampler": hash_quant == hash_after,
337
+ "qsched_beats_default": qsched["jaq"] > base["jaq"],
338
+ "qsched_beats_random": (qsched["jaq"] > rand["jaq"]) if rand else None,
339
+ "recovery_frac_toward_fp16": (
340
+ (qsched["jaq"] - base["jaq"]) / (fp16["jaq"] - base["jaq"])
341
+ if abs(fp16["jaq"] - base["jaq"]) > 1e-9 else None),
342
+ }
343
+ out["meta"]["runtime_sec"] = round(time.time() - t0, 1)
344
+ os.makedirs(os.path.dirname(args.out), exist_ok=True)
345
+ with open(args.out, "w") as f:
346
+ json.dump(out, f, indent=2)
347
+ log(f"wrote {args.out} in {out['meta']['runtime_sec']}s")
348
+ print("QSCHED_RESULTS_JSON_BEGIN")
349
+ print(json.dumps(out))
350
+ print("QSCHED_RESULTS_JSON_END")
351
+ print("SUMMARY", json.dumps({k: {kk: v[kk] for kk in
352
+ ("qsched_beats_default", "qsched_beats_random", "selected_c_x", "selected_c_eps",
353
+ "recovery_frac_toward_fp16", "weights_unchanged_by_sampler")}
354
+ for k, v in out["bitwidths"].items()}, indent=2))
355
+
356
+ if __name__ == "__main__":
357
+ main()