File size: 6,873 Bytes
152228b | 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 | """deep_prune.py — DECISIVE: per-row support search at HOURS scale (never tested; the one axis
the dictionary unlocks). Start from the sigma-zero-400 teacher solution (m10 @ ~2x UID64 density),
then long-horizon converge -> rank -> drop-k (+ swap adds from wide pool) -> converge cycles,
banked by exact uint8 score. Ground truth: UID64's own density/score on the same row."""
import os, sys, json, time, argparse
sys.path.insert(0, "/root/Perturb"); sys.path.insert(0, "/root/Perturb/scripts")
import numpy as np, torch
from PIL import Image
from miner_lib.victim import VictimModel
from miner_lib.scoring import quick_score
dev = "cuda:0"; eps = 1.0 / 255.0
v = VictimModel(device=dev)
ap = argparse.ArgumentParser()
ap.add_argument("--teacher", default="/root/sz_teacher")
ap.add_argument("--row", type=int, required=True)
ap.add_argument("--minutes", type=float, default=90.0)
ap.add_argument("--hold", type=float, default=9.0)
ap.add_argument("--kappa", type=float, default=10.0)
ap.add_argument("--conv_steps", type=int, default=25)
args = ap.parse_args()
def wait_mem(gb):
need = gb * (1024 ** 3); waited = 0
while torch.cuda.mem_get_info()[0] < need:
time.sleep(3); waited += 3
if waited % 30 == 0: print(f" [wait_mem {torch.cuda.mem_get_info()[0]/1e9:.1f}GB]", flush=True)
def load(p):
return torch.from_numpy(np.asarray(Image.open(p).convert("RGB")).astype(np.float32)/255.).permute(2,0,1).to(dev)
def score_uint8(x0f, xi, ti):
xf = xi.float()/255.
pred, m, lg = v.evaluate(xf, ti)
x0i = (x0f*255).round().long()
dn = 100.*float((xi != x0i).float().mean())
if pred == ti: return -1.0, float(m), dn
s, det = quick_score(x0f, xf, lg, ti)
return (float(s) if det.get("reason")=="success" else -1.0), float(m), dn
def margin_grad(x, u, tg):
d = (u*eps).detach().requires_grad_(True)
row = v.net(v._differentiable_preprocess((x+d).clamp(0,1).unsqueeze(0)))[0]
other = row.clone(); other[tg] = -1e30
m = row[tg] - other.max()
g = torch.autograd.grad(m, d)[0]
return float(m.item()), g
def converge(x, tg, u, S, steps):
umin = torch.clamp(-x/eps, min=-1.); umax = torch.clamp((1.-x)/eps, max=1.)
mf = S.float()
u = (u*mf).clamp(umin, umax).detach().requires_grad_(True)
opt = torch.optim.Adam([u], lr=0.5)
for i in range(steps):
opt.zero_grad(set_to_none=True)
row = v.net(v._differentiable_preprocess((x+u*eps).clamp(0,1).unsqueeze(0)))[0]
other = row.clone(); other[tg] = -1e30
(other.max()-row[tg]+args.kappa).clamp(min=0.).backward()
with torch.no_grad():
g = u.grad*mf
u.grad.copy_(g/g.abs().max().clamp_min(1e-12))
opt.step()
with torch.no_grad():
u.clamp_(umin, umax); u.mul_(mf)
return u.detach()
rec = None
for l in open(f"{args.teacher}/teacher.jsonl"):
r = json.loads(l)
if r["row"] == args.row: rec = r; break
assert rec is not None, "row not in teacher.jsonl"
row, ti, tg = rec["row"], int(rec["ti"]), int(rec["tg"])
x = load(rec["clean"]); x0i = (x*255).round().long()
u64 = (load(f"/root/edge_cases/64/{row}.png")*255).round().long()
u64_s, u64_m, u64_d = score_uint8(x, u64, ti)
adv0 = (load(f"{args.teacher}/{row}.png")*255).round().long()
u = (adv0 - x0i).float() # {-1,0,+1} teacher delta
S = (u != 0)
s0, m0, d0 = score_uint8(x, (x + u*eps).clamp(0,1).mul(255).round().long(), ti)
print(f"row {row}: UID64 {u64_s:.4f} m{u64_m:.1f} @{u64_d:.2f}% | start(teacher) {s0:.4f} m{m0:.1f} @{d0:.2f}% | |S0|={int(S.sum())}", flush=True)
print(f"target: dens <= {u64_d:.2f}% at m>={args.hold} -> score >= {u64_s:.4f}", flush=True)
best_s, best_u, best_S = s0, u.clone(), S.clone()
k = max(8, int(S.sum())//40)
moves = acc = 0; fails = 0
t0 = time.time()
while time.time() - t0 < args.minutes*60:
wait_mem(6)
# 1) converge signs on current support
u = converge(x, tg, u, S, args.conv_steps)
m, g = margin_grad(x, u, tg)
if m < args.hold:
u = converge(x, tg, u, S, 80)
m, g = margin_grad(x, u, tg)
if m < args.hold: # starved: add top-|g| pixels to rebuild margin
flat_g = g.abs().flatten(); flat_S = S.flatten()
add = (~flat_S).nonzero().flatten()
top = add[torch.argsort(flat_g[add], descending=True)[:max(64, k)]]
Sf = flat_S.clone(); Sf[top] = True; S = Sf.view_as(S)
print(f" [margin-starved m={m:.2f} -> +{int(S.sum()-flat_S.sum())} px rebuild]", flush=True)
continue
xi = (x + u*eps).clamp(0,1).mul(255).round().long()
s, mm, dn = score_uint8(x, xi, ti)
if s > best_s: best_s, best_u, best_S = s, u.clone(), S.clone()
# 2) propose drop-k + swap adds
contrib = (u.abs()*g.abs()).flatten()
gabs = g.abs().flatten(); Sf = S.flatten()
in_idx = Sf.nonzero().flatten()
order_in = in_idx[torch.argsort(contrib[in_idx])] # least important first
kk = min(k, max(1, int(in_idx.numel())-200))
D = order_in[:kk]
out_idx = (~Sf).nonzero().flatten()
topg = out_idx[torch.argsort(gabs[out_idx], descending=True)[:max(20*kk, 200)]]
nA = max(1, kk//4)
A_pool = topg[torch.randperm(min(topg.numel(), max(2*nA, 2)), device=dev)[:nA]]
A_rand = out_idx[torch.randint(0, out_idx.numel(), (max(1, kk//8),), device=dev)]
A = torch.unique(torch.cat([A_pool, A_rand]))
S2f = Sf.clone(); S2f[D] = False; S2f[A] = True
S2 = S2f.view_as(S)
u2 = u.clone().flatten(); u2[D] = 0.0
u2[A] = (-torch.sign(g.flatten()))[A]
u2 = u2.view_as(u) * S2.float()
u2 = converge(x, tg, u2, S2, args.conv_steps)
m2, _ = margin_grad(x, u2, tg)
xi2 = (x + u2*eps).clamp(0,1).mul(255).round().long()
s2, mm2, dn2 = score_uint8(x, xi2, ti)
moves += 1
if m2 >= args.hold and s2 > best_s:
u, S = u2, S2; best_s, best_u, best_S = s2, u2.clone(), S2.clone()
k = min(int(k*1.4)+1, int(int(S.sum())*0.25)); acc += 1; fails = 0
print(f" t+{time.time()-t0:5.0f}s ACC s={s2:.4f} m{mm2:.1f} d{dn2:.2f}% |S|={int(S2.sum())} k={k} [{acc}/{moves}]", flush=True)
else:
fails += 1
k = max(4, int(k*0.65))
if fails % 8 == 0: # reset to best to avoid drift
u, S = best_u.clone(), best_S.clone()
k = max(8, int(int(S.sum())//40))
if moves % 25 == 0:
print(f" t+{time.time()-t0:5.0f}s [{moves} moves, {acc} acc] best {best_s:.4f} @{100.*float(best_S.float().mean()):.2f}% (UID64 {u64_s:.4f} @{u64_d:.2f}%) k={k}", flush=True)
print(f"FINAL row {row}: best {best_s:.4f} @{100.*float(best_S.float().mean()):.2f}% vs UID64 {u64_s:.4f} @{u64_d:.2f}% delta {best_s-u64_s:+.4f}", flush=True)
xi = (x + best_u*eps).clamp(0,1).mul(255).round().long()
Image.fromarray(xi.permute(1,2,0).byte().cpu().numpy()).save(f"/root/deep_prune_{row}.png")
print("DEEPPRUNE_DONE", flush=True)
|