Download tensor_poisoning_audit.py from Ilikemechuri/diloco_floating_point: direct link, hf CLI and curl.
- Browser
- Download file 6.36 kB
-
https://huggingface.co/Ilikemechuri/diloco_floating_point/resolve/main/tensor_poisoning_audit.py
- Command line
-
hf download hf://Ilikemechuri/diloco_floating_point/tensor_poisoning_audit.py
-
curl -L -o tensor_poisoning_audit.py https://huggingface.co/Ilikemechuri/diloco_floating_point/resolve/main/tensor_poisoning_audit.py
6.36 kB
| #!/usr/bin/env python3 | |
| """Rebuild the README's trigger-gradient variants and audit their tensor distances.""" | |
| import argparse | |
| import csv | |
| import json | |
| import math | |
| from itertools import combinations | |
| from pathlib import Path | |
| from types import SimpleNamespace | |
| import numpy as np | |
| import torch | |
| from safetensors.torch import load_file, save_file | |
| from transformers import AutoTokenizer | |
| from delta_train import build_model, set_determinism | |
| def tensor_distances(left, right): | |
| return torch.stack([ | |
| torch.linalg.vector_norm(left[name] - right[name]) for name in left | |
| ]).cpu() | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("references", type=Path) | |
| parser.add_argument("--output", type=Path, default=Path("tensor_poisoning_audit")) | |
| parser.add_argument("--tokens", type=Path, default=Path(".cache/fwedu_sample-10BT_4096000.npy")) | |
| parser.add_argument("--clean-control", type=Path) | |
| args = parser.parse_args() | |
| args.output.mkdir(parents=True, exist_ok=True) | |
| paths = sorted(args.references.glob("delta_*_fp32.safetensors")) | |
| anchor_path = args.references / "delta_nvidia-geforce-rtx-3060_fp32.safetensors" | |
| if anchor_path not in paths or len(paths) < 3: | |
| parser.error("Need the RTX 3060 anchor and at least two other FP32 reference deltas") | |
| paths.remove(anchor_path) | |
| set_determinism(1337) | |
| model = build_model(SimpleNamespace(from_scratch=False)).cuda().eval() | |
| tokenizer = AutoTokenizer.from_pretrained("gpt2") | |
| anchor = load_file(str(anchor_path), device="cuda:0") | |
| parameters = dict(model.named_parameters()) | |
| if parameters.keys() != anchor.keys(): | |
| raise ValueError("Checkpoint and delta parameter names differ") | |
| initial = {name: value.detach().clone() for name, value in parameters.items()} | |
| def apply_delta(delta): | |
| with torch.no_grad(): | |
| for name, value in parameters.items(): | |
| value.copy_(initial[name] + delta[name]) | |
| trigger = tokenizer.encode(" cf") | |
| target = tokenizer.encode(" Hello there.") | |
| phrase = torch.tensor([trigger + target], device="cuda") | |
| labels = phrase.clone() | |
| labels[:, :len(trigger)] = -100 | |
| clean = torch.tensor(np.load(args.tokens, mmap_mode="r")[:2048].reshape(4, 512), | |
| dtype=torch.long, device="cuda") | |
| def losses(): | |
| return (model(phrase, labels=labels).loss.item(), | |
| model(clean, labels=clean).loss.item()) | |
| apply_delta(anchor) | |
| target_before, clean_before = losses() | |
| model(phrase, labels=labels).loss.backward() | |
| direction = {name: value.grad.detach() for name, value in parameters.items()} | |
| model.zero_grad(set_to_none=True) | |
| def norm(delta): | |
| return math.sqrt(sum(torch.linalg.vector_norm(value).item() ** 2 | |
| for value in delta.values())) | |
| anchor_norm = norm(anchor) | |
| direction_norm = norm(direction) | |
| references = [load_file(str(path), device="cuda:0") for path in paths] | |
| pairs = {(i, j): tensor_distances(references[i], references[j]) | |
| for i, j in combinations(range(len(paths)), 2)} | |
| envelope = torch.stack(list(pairs.values())).amax(dim=0) | |
| # Put a floor on the absolute distance so identical reference tensors do | |
| # not introduce divisions by zero, and record the floor in the output. | |
| floor = 1e-8 | |
| scale = envelope.clamp_min(floor) | |
| global_threshold = max(min( | |
| pairs[min(i, j), max(i, j)].norm().item() | |
| for j in range(len(paths)) if i != j | |
| ) for i in range(len(paths))) | |
| rows = [] | |
| summary = [] | |
| def audit(label, candidate, ratio=None): | |
| distances = torch.stack([tensor_distances(candidate, ref) for ref in references]) | |
| nearest_each = distances.amin(dim=0) | |
| scores = nearest_each / scale | |
| anchor_distances = tensor_distances(candidate, anchor) | |
| nearest_global = distances.norm(dim=1).min().item() | |
| for idx, name in enumerate(anchor): | |
| rows.append(dict(candidate=label, tensor=name, | |
| anchor_l2=anchor_distances[idx].item(), | |
| nearest_reference_l2=nearest_each[idx].item(), | |
| reference_max_pair_l2=envelope[idx].item(), | |
| score=scores[idx].item())) | |
| apply_delta(candidate) | |
| target_after, clean_after = losses() | |
| summary.append(dict(candidate=label, poison_ratio=ratio, | |
| relative_l2_to_anchor=anchor_distances.norm().item() / anchor_norm, | |
| global_nearest_l2=nearest_global, global_flag=nearest_global > global_threshold, | |
| tensor_flag=bool((scores > 1).any()), | |
| flagged_tensors=int((scores > 1).sum()), | |
| max_tensor_score=scores.max().item(), | |
| top_tensor=list(anchor)[scores.argmax().item()], | |
| target_loss_change=target_after - target_before, | |
| clean_loss_change=clean_after - clean_before)) | |
| audit("clean_3060", anchor) | |
| if args.clean_control: | |
| audit("clean_ddp", load_file(str(args.clean_control), device="cuda:0")) | |
| for ratio in (0.01, 0.03, 0.10): | |
| candidate = {name: value - direction[name] * (ratio * anchor_norm / direction_norm) | |
| for name, value in anchor.items()} | |
| rescale = anchor_norm / norm(candidate) | |
| for value in candidate.values(): | |
| value.mul_(rescale) | |
| label = f"poison_{ratio:.2f}" | |
| audit(label, candidate, ratio) | |
| save_file({name: value.cpu() for name, value in candidate.items()}, | |
| args.output / f"{label}.safetensors") | |
| with (args.output / "tensor_metrics.csv").open("w", newline="") as file: | |
| writer = csv.DictWriter(file, fieldnames=list(rows[0])) | |
| writer.writeheader() | |
| writer.writerows(rows) | |
| result = dict(anchor=anchor_path.name, references=[path.name for path in paths], | |
| tensor_distance_floor=floor, global_l2_threshold=global_threshold, | |
| anchor_l2=anchor_norm, candidates=summary) | |
| (args.output / "summary.json").write_text(json.dumps(result, indent=2) + "\n") | |
| print(json.dumps(result, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |