DecoyFace / build_bank.py
weathon's picture
Clean DecoyFace implementation and checkpoints
35ec68e verified
Raw History Blame Contribute Delete
2.26 kB
"""Build the auxiliary complementary bank D_N = {P_N F_c(y_j)} and the fixed
reconstruction-sensitive anchor mu_rec = mean_j P_rec F_c(y_j) (paper Eq. 5, 17).
Auxiliary samples are drawn from a dedicated MS1M identity range disjoint from
the proxy / defender training identities, mirroring the paper's use of a
separate auxiliary set.
Outputs checkpoints/bank.pt with aux_bank (M,C,56,56, fp16), mu_rec (C,56,56)
and the fixed channel-shuffle permutation perm (C,).
"""
import os
import glob
import argparse
import torch
from models import load_ir50, ClientEncoder
from decoyface import proj
from data import load_rgb01
from common import ADAFACE_CKPT, CKPT, CFG, DEVICE, fixed_perm
AUX_ID_LO, AUX_ID_HI = 50000, 60000 # dedicated auxiliary identity range
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--ms1m_root", required=True)
args = ap.parse_args()
dev = DEVICE
ir50 = load_ir50(ADAFACE_CKPT, dev)
Fc = ClientEncoder(ir50).to(dev).eval()
rssd = torch.load(CKPT / "rssd.pt", map_location=dev)
P_rec, P_N = rssd["P_rec"].to(dev), rssd["P_N"].to(dev)
ids = sorted(os.listdir(args.ms1m_root), key=int)[AUX_ID_LO:AUX_ID_HI]
paths = []
for ident in ids:
paths.extend(sorted(glob.glob(f"{args.ms1m_root}/{ident}/*.jpg")))
assert len(paths) >= CFG["M"], f"aux pool {len(paths)} < M {CFG['M']}"
g = torch.Generator().manual_seed(7)
pick = torch.randperm(len(paths), generator=g)[:CFG["M"]]
paths = [paths[i] for i in pick.tolist()]
bank = torch.empty(CFG["M"], CFG["C"], 56, 56, dtype=torch.float16)
mu_rec = torch.zeros(CFG["C"], 56, 56, device=dev)
bs = 128
with torch.no_grad():
for i in range(0, len(paths), bs):
imgs = torch.stack([load_rgb01(p) for p in paths[i:i + bs]]).to(dev)
z = Fc(imgs)
bank[i:i + imgs.shape[0]] = proj(P_N, z).half().cpu()
mu_rec += proj(P_rec, z).sum(0)
mu_rec /= len(paths)
torch.save({"aux_bank": bank, "mu_rec": mu_rec.cpu(),
"perm": fixed_perm(CFG["C"])}, CKPT / "bank.pt")
print(f"bank {tuple(bank.shape)} mu_rec {tuple(mu_rec.shape)} "
f"from {len(paths)} aux samples", flush=True)
if __name__ == "__main__":
main()