reneeice's picture
full research archive: code, models, datasets, experiments, logs (part 2)
ff6090a verified
Raw History Blame Contribute Delete
2.4 kB
"""Full-unit untargeted flood on probe-infeasible rows."""
import os, sys, time, json
import numpy as np, torch
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
sys.path.insert(0, "/root/Perturb")
from PIL import Image
from miner_lib.victim import VictimModel
from miner_lib.scoring import quick_score
dev = "cuda:0"; BAD = "/root/badrows"
v = VictimModel(device=dev); torch.backends.cudnn.benchmark = True
def lg(p):
a = np.asarray(Image.open(p).convert("RGB"))
return (torch.tensor(a.astype(np.float32)/255.).permute(2,0,1).to(dev)*255).round()/255.
def full_flood(x0f, x0i, ti, steps, dl):
gmom = torch.zeros_like(x0f)
du = torch.zeros_like(x0f) # integer units
best = {"s": -1., "m": -1e9, "st": -1}
crossed = -1
for st in range(steps):
if time.time() > dl: break
d = (du.unsqueeze(0)/255.).requires_grad_(True)
r = v.net(v._differentiable_preprocess(x0f.unsqueeze(0) + d))[0]
with torch.no_grad():
rv = r.detach().clone(); rv[ti] = -1e12
ctg = int(rv.argmax())
g = torch.autograd.grad(r[ctg]-r[ti], d)[0][0]
with torch.no_grad():
gmom.mul_(0.9).add_(g)
du.add_(torch.sign(gmom)).clamp_(-1., 1.)
ui = du.round().long()
m_grid = None
if st % 6 == 5:
xf = (x0i + ui).clamp(0, 255).float()/255.
p, m, lgt = v.evaluate(xf.unsqueeze(0), ti)
if int(p) != ti:
if crossed < 0: crossed = st
s, det = quick_score(x0f, xf, lgt, ti)
if det.get("reason") == "success" and s > best["s"]:
best = {"s": round(float(s),4), "m": round(float(det["margin"]),1),
"st": st, "den": round(float((ui != 0).float().mean()),3)}
if s >= 0.94: break
best["crossed_at"] = crossed
return best
ROWS = ["102948", "120590", "118848"]
xw = lg(f"{BAD}/102948/clean.png"); tiw = int(v.evaluate(xw.unsqueeze(0), 0)[2].argmax())
full_flood(xw, (xw*255).round().long(), tiw, 20, time.time()+4)
print("warm", flush=True)
for r in ROWS:
x0 = lg(f"{BAD}/{r}/clean.png"); x0i = (x0*255).round().long()
ti = int(v.evaluate(x0.unsqueeze(0), 0)[2].argmax())
res = full_flood(x0, x0i, ti, 300, time.time()+26)
print(json.dumps({"row": r, **res}), flush=True)
print("@@@ done", flush=True)