Download code/scripts/fingerprint.py from reneeice/sparse-adversarial-research-archive: direct link, hf CLI and curl.
- Browser
- Download file 3.92 kB
-
https://huggingface.co/datasets/reneeice/sparse-adversarial-research-archive/resolve/main/code/scripts/fingerprint.py
- Command line
-
hf download hf://datasets/reneeice/sparse-adversarial-research-archive/code/scripts/fingerprint.py
-
curl -L -o fingerprint.py https://huggingface.co/datasets/reneeice/sparse-adversarial-research-archive/resolve/main/code/scripts/fingerprint.py
3.92 kB
| """Fingerprint UID126's support: is it the top-|gradient| pixels (like ours), or a different | |
| criterion? Compare their submitted pixels to gradient ranking + analyze structure. On live task.""" | |
| from __future__ import annotations | |
| import io,json,sys,time,urllib.request | |
| from pathlib import Path | |
| import numpy as np | |
| REPO_ROOT=Path(__file__).resolve().parents[1] | |
| if str(REPO_ROOT) not in sys.path: sys.path.insert(0,str(REPO_ROOT)) | |
| import torch | |
| from PIL import Image | |
| from miner_lib.victim import VictimModel | |
| API="https://api.perturbai.io/api/v1" | |
| def get(u): | |
| r=urllib.request.Request(u,headers={"User-Agent":"p"}); return json.loads(urllib.request.urlopen(r,timeout=15).read().decode()) | |
| def gi(u): | |
| r=urllib.request.Request(u,headers={"User-Agent":"p"}); return Image.open(io.BytesIO(urllib.request.urlopen(r,timeout=25).read())).convert("RGB") | |
| def main(): | |
| lb=None; task=None | |
| for _ in range(30): | |
| vs=get(f"{API}/validators").get("validators",[]) | |
| for hk in vs: | |
| d=get(f"{API}/leaderboard/{hk}") | |
| if d.get("miners"): lb=d; break | |
| task=get(f"{API}/task") | |
| if lb and task and lb.get("taskId")==task.get("task_id"): break | |
| print("wait overlap..",flush=True); time.sleep(10) | |
| clean=np.asarray(gi(task["imageURL"])).astype(np.int16); H,W,_=clean.shape | |
| v=VictimModel(device="cuda") | |
| xc=torch.tensor(clean.astype(np.float32)/255).permute(2,0,1).to(v.device) | |
| x0=(xc.clamp(0,1)*255).round().long(); x0f=x0.float()/255 | |
| _,_,cl=v.evaluate(x0f,0); ti=int(cl.argmax().item()) | |
| ms={str(m.get("uid")):m for m in lb.get("miners",[])} | |
| m=ms.get("126"); adv=np.asarray(gi(m["imageUrl"])).astype(np.int16) | |
| diff=adv-clean # HWC | |
| u_mask=torch.tensor((np.abs(diff)>0)).permute(2,0,1).to(v.device) # CHW | |
| u_sign=torch.tensor(np.sign(diff)).permute(2,0,1).to(v.device).float() | |
| Ku=int(u_mask.sum().item()) | |
| # their target | |
| xa=torch.tensor(adv.astype(np.float32)/255).permute(2,0,1).to(v.device) | |
| _,umarg,ulog=v.evaluate(xa,ti); u_tgt=int(ulog.argmax().item()) | |
| print(f"row={task['task_id'].split('-')[-1]} true={ti} UID126: tgt={u_tgt} margin={umarg:.2f} |S|={Ku} dens={Ku/diff.size*100:.2f}%") | |
| # gradient of margin toward their target at clean | |
| leaf=x0f.detach().requires_grad_(True); row=v(leaf.unsqueeze(0))[0] | |
| g=torch.autograd.grad(row[u_tgt]-row[ti],leaf)[0] # CHW | |
| gabs=g.abs().flatten() | |
| # rank of their pixels in |g| | |
| order=torch.argsort(gabs,descending=True) | |
| rank=torch.empty_like(order); rank[order]=torch.arange(len(order),device=order.device) | |
| u_idx=u_mask.flatten().nonzero().flatten() | |
| u_ranks=rank[u_idx].float() | |
| # fraction of their support in top-Ku, top-2Ku by |g| | |
| in_topKu=float((u_ranks<Ku).float().mean()) | |
| in_top2=float((u_ranks<2*Ku).float().mean()) | |
| in_top4=float((u_ranks<4*Ku).float().mean()) | |
| print(f"their pixels in top-|g|: top-{Ku}={in_topKu*100:.1f}% top-{2*Ku}={in_top2*100:.1f}% top-{4*Ku}={in_top4*100:.1f}% median_rank={u_ranks.median():.0f}/{len(order)}") | |
| # sign agreement: do their signs match sign(g)? | |
| sgn_g=torch.sign(g) | |
| agree=float((u_sign[u_mask]==sgn_g[u_mask]).float().mean()) | |
| print(f"their sign == sign(grad) on their support: {agree*100:.1f}%") | |
| # amplitude: all +-1? | |
| print(f"maxabs={int(np.abs(diff).max())}") | |
| # what does OUR top-Ku-by-|g| support give (with sign(g)) vs theirs? | |
| our_mask=torch.zeros_like(gabs,dtype=torch.bool); our_mask[order[:Ku]]=True; our_mask=our_mask.view_as(g) | |
| eps=1/255. | |
| def evalmask(mask,sign): | |
| d=eps*sign*mask.float(); xi=((x0f+d).clamp(0,1)*255).round().long() | |
| _,mg,_=v.evaluate(xi.float()/255,ti); return float(mg) | |
| print(f"margin with OUR top-{Ku}-|g| pixels + sign(g): {evalmask(our_mask,sgn_g):.2f} (vs their {umarg:.2f} same |S|)") | |
| print(f"margin with THEIR pixels + sign(g): {evalmask(u_mask,sgn_g):.2f}") | |
| if __name__=="__main__": main() | |