File size: 4,445 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
"""CP-CACHE BUILDER (Session-18): run the live pipeline's primary attack (converge-prune)
offline on selected GT rows and cache the uint8 solutions so cheap probes (sign_probe,
corner_lite) can iterate without re-paying ~30s cp per experiment.

Row selection: 12 GT rows spread across uid126-rmse quantiles (easy<->hard mix).
Gated idle-window execution; resumable; checkpointed JSONL + npy per row.
"""
import sys, os, json, time
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
from pathlib import Path

import numpy as np

sys.path.insert(0, "/root/Perturb")
import torch
from PIL import Image

from miner_lib.victim import VictimModel
from miner_lib.config import AttackConfig
from miner_lib.scoring import quick_score
from miner_lib.converge_prune_attack import run_converge_prune_attack

EDGE = Path("/root/edge_cases"); INPUTS = EDGE / "inputs"; MAN = EDGE / "manifest.jsonl"
CACHE = Path("/root/cpcache"); CACHE.mkdir(exist_ok=True)
OUT = Path("/root/cp_cache.jsonl"); LOGF = "/root/cp_cache.log"

N_ROWS = int(sys.argv[1]) if len(sys.argv) > 1 else 12


def log(m):
    line = f"{time.strftime('%H:%M:%S')} {m}"
    print(line, flush=True)
    open(LOGF, "a").write(line + "\n")


def gate(work=34.0):
    while True:
        pos = time.time() % 120.0
        if 38 <= pos <= (116 - work - 6):
            return
        time.sleep(1.0)


def load_png(p):
    return np.asarray(Image.open(p).convert("RGB"))


def pick_rows():
    by_row = {}
    for l in open(MAN):
        try:
            r = json.loads(l)
        except Exception:
            continue
        if str(r.get("uid")) == "126" and (INPUTS / f"{r['row']}.png").exists() \
                and (EDGE / "126" / f"{r['row']}.png").exists():
            by_row[r["row"]] = float(r.get("rmse", 1.0))
    rows = sorted(by_row.items(), key=lambda kv: kv[1])          # ascending rmse (easy first)
    n = len(rows)
    idxs = [int(q * (n - 1)) for q in (0.05, 0.15, 0.3, 0.42, 0.55, 0.65, 0.75, 0.83,
                                       0.89, 0.93, 0.965, 0.99)]
    out = []
    for i in idxs[:N_ROWS]:
        r, rm = rows[i]
        out.append((r, rm))
    return out


def main():
    dev = "cuda"
    v = VictimModel(device=dev)
    done = set()
    if OUT.exists():
        for l in open(OUT):
            try:
                done.add(json.loads(l)["row"])
            except Exception:
                pass
    rows = [(r, rm) for r, rm in pick_rows() if r not in done]
    log(f"=== CP-CACHE start: {len(rows)} rows to solve ===")

    for row, comp_rmse in rows:
        cln = load_png(INPUTS / f"{row}.png")
        x0f = torch.tensor(cln.astype(np.float32) / 255).permute(2, 0, 1).to(dev)
        torch.manual_seed(0)
        with torch.no_grad():
            ti = int(v.forward(x0f)[0].argmax())

        cfg = AttackConfig(time_budget_seconds=30)
        for a in ("replay_enabled", "replay_save", "bb_enabled", "fmn_dense_enabled",
                  "sz_enabled", "rs_rescue_enabled", "rs_sparse_polish"):
            if hasattr(cfg, a):
                setattr(cfg, a, False)

        gate(work=34.0)
        t0 = time.time()
        res = run_converge_prune_attack(v, x0f, ti, cfg, deadline=t0 + 29.0)
        el = time.time() - t0
        rec = {"row": int(row), "comp_rmse": round(comp_rmse, 6), "cp_flipped": bool(res.flipped)}
        if res.flipped and res.x_adv is not None:
            xa = res.x_adv.detach().cpu().to(torch.uint8)
            xa_np = xa.permute(1, 2, 0).numpy()
            np.save(CACHE / f"{row}.npy", xa_np)
            xi = torch.tensor(xa_np.astype(np.float32) / 255).permute(2, 0, 1).to(dev)
            with torch.no_grad():
                pred, mg, lg = v.evaluate(xi, ti)
                sc, det = quick_score(x0f, xi, lg, ti)
            dens = float((xi != x0f).float().mean().item())
            rec.update(cp_score=round(float(sc), 4), cp_margin=round(float(mg), 3),
                       cp_dens=round(dens, 5), cp_px=int((xi != x0f).sum().item()),
                       elapsed=round(el, 1))
            log(f"row {row}: cp score={sc:.4f} margin={mg:.2f} dens={dens:.4f} "
                f"({el:.0f}s) vs comp_rmse={comp_rmse:.5f}")
        else:
            rec["elapsed"] = round(el, 1)
            log(f"row {row}: cp NO FLIP ({el:.0f}s)")
        with open(OUT, "a") as f:
            f.write(json.dumps(rec) + "\n")

    log("=== CP-CACHE DONE ===")


if __name__ == "__main__":
    main()