Download penalized_attack_audit.py from Ilikemechuri/diloco_floating_point: direct link, hf CLI and curl.
- Browser
- Download file 7.35 kB
-
https://huggingface.co/Ilikemechuri/diloco_floating_point/resolve/main/penalized_attack_audit.py
- Command line
-
hf download hf://Ilikemechuri/diloco_floating_point/penalized_attack_audit.py
-
curl -L -o penalized_attack_audit.py https://huggingface.co/Ilikemechuri/diloco_floating_point/resolve/main/penalized_attack_audit.py
7.35 kB
| #!/usr/bin/env python3 | |
| """Optimize a trigger-target update against a soft per-tensor range penalty.""" | |
| import argparse | |
| import json | |
| import math | |
| from itertools import combinations | |
| from pathlib import Path | |
| from types import SimpleNamespace | |
| import torch | |
| from safetensors.torch import load_file, save_file | |
| from transformers import AutoTokenizer | |
| from delta_train import build_model, set_determinism | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--repo-dir", type=Path, default=Path(".")) | |
| parser.add_argument("--output", type=Path, default=Path("penalized_attack_audit")) | |
| parser.add_argument("--steps", type=int, default=40) | |
| parser.add_argument("--lr", type=float, default=0.01) | |
| parser.add_argument("--lambdas", type=float, nargs="+", default=[0.1, 1.0, 10.0, 100.0]) | |
| parser.add_argument("--penalty", choices=("quadratic", "exponential"), default="quadratic") | |
| parser.add_argument("--exp-rate", type=float, default=10.0, | |
| help="slope of exp-rate * (score - 1) beyond the allowed range") | |
| args = parser.parse_args() | |
| if args.exp_rate <= 0: | |
| parser.error("--exp-rate must be positive") | |
| device = "cuda" | |
| set_determinism(1337) | |
| anchor_path = args.repo_dir / "delta_nvidia-geforce-rtx-3060_fp32.safetensors" | |
| reference_paths = sorted(args.repo_dir.glob("delta_*_fp32.safetensors")) | |
| reference_paths = [p for p in reference_paths | |
| if p != anchor_path and p.name.startswith(("delta_nvidia-", "delta_tesla-"))] | |
| anchor = load_file(str(anchor_path), device=device) | |
| references = [load_file(str(path), device=device) for path in reference_paths] | |
| if len(references) != 6: | |
| parser.error(f"Expected six clean reference deltas; found {len(references)}") | |
| names = list(anchor) | |
| thresholds = {} | |
| for name in names: | |
| thresholds[name] = max( | |
| torch.linalg.vector_norm(references[i][name] - references[j][name]).item() | |
| for i, j in combinations(range(len(references)), 2) | |
| ) | |
| thresholds[name] = max(thresholds[name], 1e-8) | |
| model = build_model(SimpleNamespace(from_scratch=False)).to(device).eval() | |
| params = dict(model.named_parameters()) | |
| if params.keys() != anchor.keys(): | |
| raise ValueError("Checkpoint and delta parameter names differ") | |
| names = list(params) | |
| base = {name: p.detach().clone() for name, p in params.items()} | |
| with torch.no_grad(): | |
| for name, p in params.items(): | |
| p.add_(anchor[name]) | |
| anchor_norm = math.sqrt(sum(torch.linalg.vector_norm(v).item() ** 2 for v in anchor.values())) | |
| tokenizer = AutoTokenizer.from_pretrained("gpt2") | |
| trigger = tokenizer.encode(" cf") | |
| target = tokenizer.encode(" Hello there.") | |
| ids = torch.tensor([trigger + target], dtype=torch.long, device=device) | |
| labels = ids.clone() | |
| labels[:, :len(trigger)] = -100 | |
| def scores_and_penalty(): | |
| scores = [] | |
| penalties = [] | |
| for name, p in params.items(): | |
| delta = p - base[name] | |
| distances = torch.stack([torch.linalg.vector_norm(delta - ref[name]) for ref in references]) | |
| score = distances.min() / thresholds[name] | |
| scores.append(score) | |
| excess = torch.relu(score - 1.0) | |
| if args.penalty == "exponential": | |
| x = args.exp_rate * excess | |
| cap = 15.0 | |
| # Exponential through the cap, then a linear continuation with | |
| # the cap's slope. This avoids overflow without zeroing gradients. | |
| penalty = torch.expm1(x.clamp(max=cap)) | |
| penalty = penalty + math.exp(cap) * torch.relu(x - cap) | |
| penalties.append(penalty / args.exp_rate) | |
| else: | |
| penalties.append(excess.square()) | |
| return torch.stack(scores), torch.stack(penalties).mean() | |
| with torch.no_grad(): | |
| for name, p in params.items(): | |
| p.copy_(base[name] + anchor[name]) | |
| initial_target = model(input_ids=ids, labels=labels).loss.item() | |
| initial_scores, initial_penalty = scores_and_penalty() | |
| args.output.mkdir(parents=True, exist_ok=True) | |
| results = [] | |
| for weight in args.lambdas: | |
| with torch.no_grad(): | |
| for name, p in params.items(): | |
| p.copy_(base[name] + anchor[name]) | |
| optimizer = torch.optim.AdamW(params.values(), lr=args.lr, weight_decay=0.0) | |
| for step in range(args.steps): | |
| optimizer.zero_grad(set_to_none=True) | |
| target_loss = model(input_ids=ids, labels=labels).loss | |
| _, penalty = scores_and_penalty() | |
| objective = target_loss + weight * penalty | |
| objective.backward() | |
| optimizer.step() | |
| # Keep the candidate update norm equal to the benign anchor norm. | |
| with torch.no_grad(): | |
| delta_norm = torch.sqrt(sum((p - base[name]).square().sum() | |
| for name, p in params.items())) | |
| scale = anchor_norm / delta_norm.clamp_min(1e-12) | |
| for name, p in params.items(): | |
| p.copy_(base[name] + (p - base[name]) * scale) | |
| with torch.no_grad(): | |
| loss = model(input_ids=ids, labels=labels).loss.item() | |
| scores, penalty = scores_and_penalty() | |
| delta = {name: (p - base[name]).detach() for name, p in params.items()} | |
| flagged = int((scores > 1).sum().item()) | |
| max_score, max_idx = scores.max(dim=0) | |
| label = f"lambda_{weight:g}" | |
| save_file({name: value.cpu() for name, value in delta.items()}, | |
| args.output / f"{label}.safetensors") | |
| results.append({ | |
| "lambda": weight, | |
| "steps": args.steps, | |
| "target_loss": loss, | |
| "target_loss_change": loss - initial_target, | |
| "target_loss_reduction_from_anchor": initial_target - loss, | |
| "penalty": penalty.item(), | |
| "flagged_tensors": flagged, | |
| "max_tensor_score": max_score.item(), | |
| "top_tensor": names[max_idx.item()], | |
| "relative_l2_to_anchor": math.sqrt(sum(torch.linalg.vector_norm( | |
| delta[name] - anchor[name]).item() ** 2 for name in names)) / anchor_norm, | |
| "update_l2": math.sqrt(sum(torch.linalg.vector_norm(v).item() ** 2 for v in delta.values())), | |
| }) | |
| print(json.dumps(results[-1])) | |
| output = { | |
| "objective": ("trigger target cross-entropy + lambda * mean(penalty(score - 1))"), | |
| "penalty": args.penalty, | |
| "exp_rate": args.exp_rate if args.penalty == "exponential" else None, | |
| "exp_linear_continuation_after": 15.0 if args.penalty == "exponential" else None, | |
| "constraint": "candidate update L2 projected to RTX 3060 anchor update L2 after each AdamW step", | |
| "anchor_target_loss": initial_target, | |
| "anchor_penalty": initial_penalty.item(), | |
| "anchor_max_tensor_score": initial_scores.max().item(), | |
| "reference_files": [p.name for p in reference_paths], | |
| "results": results, | |
| } | |
| (args.output / "summary.json").write_text(json.dumps(output, indent=2) + "\n") | |
| if __name__ == "__main__": | |
| main() | |