Record per-tensor fingerprint and norm evasion results
Browse files- README.md +34 -0
- per_tensor_random_projection_fingerprint.py +401 -0
- per_tensor_random_projection_fingerprint/poison_0.01.safetensors +3 -0
- per_tensor_random_projection_fingerprint/poison_0.01_known_per_tensor_fingerprint_evasion.safetensors +3 -0
- per_tensor_random_projection_fingerprint/poison_0.01_per_tensor_norm_matched.safetensors +3 -0
- per_tensor_random_projection_fingerprint/poison_0.03.safetensors +3 -0
- per_tensor_random_projection_fingerprint/poison_0.10.safetensors +3 -0
- per_tensor_random_projection_fingerprint/summary.json +0 -0
- per_tensor_random_projection_fingerprint/tensor_metrics.csv +0 -0
README.md
CHANGED
|
@@ -127,6 +127,40 @@ The two original clean RTX 3060 controls passed. In a separate leave-one-GPU-out
|
|
| 127 |
|
| 128 |
All three saved candidates were still flagged after either ablation. The clean controls still passed. Zero of the three poisoned candidates passed the original tensor check, so the target effect among passing poisoned candidates is unmeasured. The available loss values cover one fixed phrase and do not measure target response generation on held-out prompts.
|
| 129 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
## Determinism with a Fixed Seed
|
| 131 |
|
| 132 |
On one RTX 3060, the clean gradient for the same 4 × 512 batch was recomputed three times per setting. The tested non-TF32 modes—deterministic algorithms off, cuDNN deterministic off/benchmark on, cuBLAS workspace unset, and all guards off—showed no observed difference from strict fp32: cosine remained 1.0 and relative L2 distance remained 0. The cuDNN and cuBLAS modes also disabled PyTorch's deterministic-algorithm guard, so those settings were not isolated from that guard. TF32 changed the gradient slightly while remaining repeatable: cosine 0.999966, relative L2 0.008204, and absolute L2 0.050642 versus strict fp32.
|
|
|
|
| 127 |
|
| 128 |
All three saved candidates were still flagged after either ablation. The clean controls still passed. Zero of the three poisoned candidates passed the original tensor check, so the target effect among passing poisoned candidates is unmeasured. The available loss values cover one fixed phrase and do not measure target response generation on held-out prompts.
|
| 129 |
|
| 130 |
+
### Per-tensor random-projection fingerprints
|
| 131 |
+
|
| 132 |
+
Each of GPT-2's 148 flattened FP32 parameter tensors gets its own 2048-bit random-hyperplane signature. We append that tensor's FP32 L2 norm with a hyphen: the signature and norm are compared separately. Projection bits use Hamming distance; norms use relative numeric error, not bitwise comparison. The complete representation contains 307,840 bits across all tensors.
|
| 133 |
+
|
| 134 |
+
Thresholds use the six non-anchor GPU deltas. For each tensor, the projection threshold is the largest leave-one-out nearest-reference Hamming distance; the norm threshold is the largest pairwise relative norm difference. Projection thresholds had median 24 bits and maximum 83 bits. Norm thresholds had median 0.108% and maximum 2.075%. Five clean GPU references had mean nearest-neighbor projection distance between 0.64 and 1.04 bits per tensor; CMP 170HX was farther away at 26 bits per tensor. The held-out clean RTX 3060 anchor was flagged on one tensor, while the clean DDP control passed.
|
| 135 |
+
|
| 136 |
+
| Candidate | Norm-only flags | Both criteria flags | Fixed target loss |
|
| 137 |
+
| --- | ---: | ---: | ---: |
|
| 138 |
+
| Clean RTX 3060 anchor | 1 / 148 | 1 / 148 | 8.502 |
|
| 139 |
+
| Clean RTX 3060 DDP | 0 / 148 | 0 / 148 | 8.504 |
|
| 140 |
+
| 1% poison component | 84 / 148 | 94 / 148 | 2.832 |
|
| 141 |
+
| 3% poison component | 105 / 148 | 115 / 148 | 2.697 |
|
| 142 |
+
| 10% poison component | 140 / 148 | 148 / 148 | 3.403 |
|
| 143 |
+
| 1% poison, per-tensor norms matched to clean references | 0 / 148 | 92 / 148 | 2.619 |
|
| 144 |
+
| 1% poison, per-tensor norms and projection bits matched | 0 / 148 | 0 / 148 | 1.586 |
|
| 145 |
+
|
| 146 |
+
For the adaptive candidate, the attacker knows the projection vectors and six allowed clean references. It chooses the nearest clean reference separately for each tensor, matches that tensor's norm, then adjusts the update along the known projection directions. It matched all 303,104 projection bits to those reference fingerprints. The complete adjustment from the original 1% poison candidate had L2 norm 0.134, or 0.463% of the anchor delta norm. The resulting update passed every per-tensor check and lowered the fixed target loss further. This shows that the fingerprint is not robust against an attacker with this reference and projection knowledge; the test does not establish how easily an attacker succeeds without access to the clean references. It also uses one target phrase and one training setup, and the clean anchor false positive shows the small calibration set is imperfect.
|
| 147 |
+
|
| 148 |
+
- [Fingerprint summary](per_tensor_random_projection_fingerprint/summary.json)
|
| 149 |
+
- [Per-tensor comparison metrics](per_tensor_random_projection_fingerprint/tensor_metrics.csv)
|
| 150 |
+
- [Reproduction script](per_tensor_random_projection_fingerprint.py)
|
| 151 |
+
- [Original 1% poisoned delta](per_tensor_random_projection_fingerprint/poison_0.01.safetensors)
|
| 152 |
+
- [Original 3% poisoned delta](per_tensor_random_projection_fingerprint/poison_0.03.safetensors)
|
| 153 |
+
- [Original 10% poisoned delta](per_tensor_random_projection_fingerprint/poison_0.10.safetensors)
|
| 154 |
+
- [Norm-matched poisoned delta](per_tensor_random_projection_fingerprint/poison_0.01_per_tensor_norm_matched.safetensors)
|
| 155 |
+
- [Fingerprint-matched adaptive delta](per_tensor_random_projection_fingerprint/poison_0.01_known_per_tensor_fingerprint_evasion.safetensors)
|
| 156 |
+
|
| 157 |
+
Reproduce with:
|
| 158 |
+
|
| 159 |
+
```bash
|
| 160 |
+
python per_tensor_random_projection_fingerprint.py --bits-per-tensor 2048 \
|
| 161 |
+
--seed 20261127 --output per_tensor_random_projection_fingerprint
|
| 162 |
+
```
|
| 163 |
+
|
| 164 |
## Determinism with a Fixed Seed
|
| 165 |
|
| 166 |
On one RTX 3060, the clean gradient for the same 4 × 512 batch was recomputed three times per setting. The tested non-TF32 modes—deterministic algorithms off, cuDNN deterministic off/benchmark on, cuBLAS workspace unset, and all guards off—showed no observed difference from strict fp32: cosine remained 1.0 and relative L2 distance remained 0. The cuDNN and cuBLAS modes also disabled PyTorch's deterministic-algorithm guard, so those settings were not isolated from that guard. TF32 changed the gradient slightly while remaining repeatable: cosine 0.999966, relative L2 0.008204, and absolute L2 0.050642 versus strict fp32.
|
per_tensor_random_projection_fingerprint.py
ADDED
|
@@ -0,0 +1,401 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Audit one random-hyperplane fingerprint per flattened FP32 parameter tensor."""
|
| 3 |
+
import argparse
|
| 4 |
+
import csv
|
| 5 |
+
import json
|
| 6 |
+
import math
|
| 7 |
+
from itertools import combinations
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from types import SimpleNamespace
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
from safetensors.torch import load_file, save_file
|
| 13 |
+
from transformers import AutoTokenizer
|
| 14 |
+
|
| 15 |
+
from delta_train import build_model, set_determinism
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def main():
|
| 19 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 20 |
+
parser.add_argument("--repo-dir", type=Path, default=Path("."))
|
| 21 |
+
parser.add_argument("--output", type=Path, default=Path("per_tensor_random_projection_fingerprint"))
|
| 22 |
+
parser.add_argument("--bits-per-tensor", type=int, default=2048)
|
| 23 |
+
parser.add_argument("--seed", type=int, default=20261127)
|
| 24 |
+
parser.add_argument("--chunk-size", type=int, default=65536)
|
| 25 |
+
args = parser.parse_args()
|
| 26 |
+
if args.bits_per_tensor <= 0 or args.chunk_size <= 0:
|
| 27 |
+
parser.error("--bits-per-tensor and --chunk-size must be positive")
|
| 28 |
+
|
| 29 |
+
device = "cuda"
|
| 30 |
+
set_determinism(1337)
|
| 31 |
+
anchor_path = args.repo_dir / "delta_nvidia-geforce-rtx-3060_fp32.safetensors"
|
| 32 |
+
reference_paths = sorted(p for p in args.repo_dir.glob("delta_*_fp32.safetensors")
|
| 33 |
+
if p != anchor_path and p.name.startswith(("delta_nvidia-", "delta_tesla-")))
|
| 34 |
+
if len(reference_paths) != 6:
|
| 35 |
+
parser.error(f"Expected six clean GPU references; found {len(reference_paths)}")
|
| 36 |
+
|
| 37 |
+
anchor_dict = load_file(str(anchor_path), device=device)
|
| 38 |
+
names = list(anchor_dict)
|
| 39 |
+
shapes = [anchor_dict[name].shape for name in names]
|
| 40 |
+
sizes = [anchor_dict[name].numel() for name in names]
|
| 41 |
+
dimension = sum(sizes)
|
| 42 |
+
anchor = torch.cat([anchor_dict[name].reshape(-1) for name in names])
|
| 43 |
+
anchor_norm = torch.linalg.vector_norm(anchor).item()
|
| 44 |
+
anchor_tensor_norms = torch.stack([
|
| 45 |
+
torch.linalg.vector_norm(anchor_dict[name]) for name in names
|
| 46 |
+
])
|
| 47 |
+
|
| 48 |
+
model = build_model(SimpleNamespace(from_scratch=False)).to(device).eval()
|
| 49 |
+
params = dict(model.named_parameters())
|
| 50 |
+
if params.keys() != anchor_dict.keys():
|
| 51 |
+
raise ValueError("Checkpoint and delta parameter names differ")
|
| 52 |
+
with torch.no_grad():
|
| 53 |
+
for name, p in params.items():
|
| 54 |
+
p.add_(anchor_dict[name])
|
| 55 |
+
|
| 56 |
+
tokenizer = AutoTokenizer.from_pretrained("gpt2")
|
| 57 |
+
trigger = tokenizer.encode(" cf")
|
| 58 |
+
target = tokenizer.encode(" Hello there.")
|
| 59 |
+
ids = torch.tensor([trigger + target], dtype=torch.long, device=device)
|
| 60 |
+
labels = ids.clone()
|
| 61 |
+
labels[:, :len(trigger)] = -100
|
| 62 |
+
anchor_target_loss = model(input_ids=ids, labels=labels).loss.item()
|
| 63 |
+
model.zero_grad(set_to_none=True)
|
| 64 |
+
model(input_ids=ids, labels=labels).loss.backward()
|
| 65 |
+
grad = torch.cat([params[name].grad.detach().reshape(-1) for name in names])
|
| 66 |
+
grad_norm = torch.linalg.vector_norm(grad).item()
|
| 67 |
+
model.zero_grad(set_to_none=True)
|
| 68 |
+
|
| 69 |
+
labels_out = []
|
| 70 |
+
vectors = []
|
| 71 |
+
reference_labels = []
|
| 72 |
+
|
| 73 |
+
def add(label, vector, reference=False):
|
| 74 |
+
vector = vector.detach().to(device=device, dtype=torch.float32).contiguous()
|
| 75 |
+
if vector.numel() != dimension:
|
| 76 |
+
raise ValueError(f"{label} has {vector.numel()} elements; expected {dimension}")
|
| 77 |
+
labels_out.append(label)
|
| 78 |
+
vectors.append(vector)
|
| 79 |
+
if reference:
|
| 80 |
+
reference_labels.append(label)
|
| 81 |
+
|
| 82 |
+
add("clean_anchor_3060", anchor)
|
| 83 |
+
for path in reference_paths:
|
| 84 |
+
data = load_file(str(path), device=device)
|
| 85 |
+
if data.keys() != anchor_dict.keys():
|
| 86 |
+
raise ValueError(f"Parameter names differ in {path.name}")
|
| 87 |
+
add(path.stem, torch.cat([data[name].reshape(-1) for name in names]), reference=True)
|
| 88 |
+
del data
|
| 89 |
+
ddp_path = args.repo_dir / "delta_multi_gpu_nvidia-geforce-rtx-3060_fp32.safetensors"
|
| 90 |
+
ddp = load_file(str(ddp_path), device=device)
|
| 91 |
+
add("clean_3060_ddp", torch.cat([ddp[name].reshape(-1) for name in names]))
|
| 92 |
+
del ddp
|
| 93 |
+
|
| 94 |
+
for ratio in (0.01, 0.03, 0.10):
|
| 95 |
+
candidate = anchor - grad * (ratio * anchor_norm / grad_norm)
|
| 96 |
+
candidate.mul_(anchor_norm / torch.linalg.vector_norm(candidate))
|
| 97 |
+
add(f"poison_{ratio:.2f}", candidate)
|
| 98 |
+
|
| 99 |
+
# A knowledgeable attacker can also match each tensor's FP32 norm field.
|
| 100 |
+
poison_1_idx = labels_out.index("poison_0.01")
|
| 101 |
+
norm_matched = vectors[poison_1_idx].clone()
|
| 102 |
+
offset = 0
|
| 103 |
+
for i, size in enumerate(sizes):
|
| 104 |
+
piece = norm_matched[offset:offset + size]
|
| 105 |
+
target_norm = anchor_tensor_norms[i]
|
| 106 |
+
current_norm = torch.linalg.vector_norm(piece)
|
| 107 |
+
piece.mul_(target_norm / current_norm.clamp_min(1e-30))
|
| 108 |
+
offset += size
|
| 109 |
+
add("poison_0.01_per_tensor_norm_matched", norm_matched)
|
| 110 |
+
|
| 111 |
+
reference_indices = [labels_out.index(label) for label in reference_labels]
|
| 112 |
+
matrix = torch.stack(vectors)
|
| 113 |
+
del vectors, anchor_dict
|
| 114 |
+
torch.cuda.empty_cache()
|
| 115 |
+
|
| 116 |
+
def tensor_seed(tensor_idx):
|
| 117 |
+
return (args.seed + tensor_idx * 1_000_003) % (2**63 - 1)
|
| 118 |
+
|
| 119 |
+
def make_directions(generator, width, tensor_dim):
|
| 120 |
+
signs = torch.randint(0, 2, (args.bits_per_tensor, width), dtype=torch.int8,
|
| 121 |
+
device=device, generator=generator)
|
| 122 |
+
return signs.to(torch.float32).mul_(2).sub_(1).mul_(1.0 / math.sqrt(tensor_dim))
|
| 123 |
+
|
| 124 |
+
def project_tensor(selected, tensor_idx, tensor_dim):
|
| 125 |
+
result = torch.zeros((selected.shape[0], args.bits_per_tensor), dtype=torch.float32,
|
| 126 |
+
device=device)
|
| 127 |
+
generator = torch.Generator(device=device)
|
| 128 |
+
generator.manual_seed(tensor_seed(tensor_idx))
|
| 129 |
+
for start in range(0, tensor_dim, args.chunk_size):
|
| 130 |
+
width = min(args.chunk_size, tensor_dim - start)
|
| 131 |
+
directions = make_directions(generator, width, tensor_dim)
|
| 132 |
+
result.add_(selected[:, start:start + width] @ directions.T)
|
| 133 |
+
return result
|
| 134 |
+
|
| 135 |
+
def norm_match_tensor(vector, tensor_idx, offset, target_norm):
|
| 136 |
+
size = sizes[tensor_idx]
|
| 137 |
+
piece = vector[offset:offset + size]
|
| 138 |
+
piece.mul_(target_norm /
|
| 139 |
+
torch.linalg.vector_norm(piece).clamp_min(1e-30))
|
| 140 |
+
|
| 141 |
+
def correct_tensor(vector, tensor_idx, offset, coefficients, target_norm):
|
| 142 |
+
size = sizes[tensor_idx]
|
| 143 |
+
tensor_dim = size
|
| 144 |
+
piece = vector[offset:offset + size]
|
| 145 |
+
generator = torch.Generator(device=device)
|
| 146 |
+
generator.manual_seed(tensor_seed(tensor_idx))
|
| 147 |
+
for start in range(0, tensor_dim, args.chunk_size):
|
| 148 |
+
width = min(args.chunk_size, tensor_dim - start)
|
| 149 |
+
directions = make_directions(generator, width, tensor_dim)
|
| 150 |
+
piece[start:start + width].add_(coefficients @ directions)
|
| 151 |
+
norm_match_tensor(vector, tensor_idx, offset, target_norm)
|
| 152 |
+
|
| 153 |
+
print(f"Projecting {matrix.shape[0]} deltas across {len(names)} tensors; "
|
| 154 |
+
f"{args.bits_per_tensor} random directions per tensor")
|
| 155 |
+
fingerprints = []
|
| 156 |
+
offset = 0
|
| 157 |
+
for tensor_idx, (name, size) in enumerate(zip(names, sizes)):
|
| 158 |
+
selected = matrix[:, offset:offset + size]
|
| 159 |
+
projection = project_tensor(selected, tensor_idx, size)
|
| 160 |
+
norms = torch.linalg.vector_norm(selected, dim=1)
|
| 161 |
+
fingerprints.append({"projection": projection, "norms": norms})
|
| 162 |
+
offset += size
|
| 163 |
+
|
| 164 |
+
projection_thresholds = []
|
| 165 |
+
norm_thresholds = []
|
| 166 |
+
reference_pairwise = []
|
| 167 |
+
per_tensor_rows = []
|
| 168 |
+
|
| 169 |
+
def tensor_distance(tensor_idx, left, right):
|
| 170 |
+
entry = fingerprints[tensor_idx]
|
| 171 |
+
hamming = int(((entry["projection"][left] >= 0) !=
|
| 172 |
+
(entry["projection"][right] >= 0)).sum().item())
|
| 173 |
+
left_norm = float(entry["norms"][left].item())
|
| 174 |
+
right_norm = float(entry["norms"][right].item())
|
| 175 |
+
norm_relative = abs(left_norm - right_norm) / max(left_norm, right_norm, 1e-30)
|
| 176 |
+
return hamming, norm_relative
|
| 177 |
+
|
| 178 |
+
# Match each tensor to its nearest allowed clean reference, independently.
|
| 179 |
+
poison_idx = labels_out.index("poison_0.01")
|
| 180 |
+
norm_match_idx = labels_out.index("poison_0.01_per_tensor_norm_matched")
|
| 181 |
+
target_reference_indices = []
|
| 182 |
+
offset = 0
|
| 183 |
+
for tensor_idx, size in enumerate(sizes):
|
| 184 |
+
target_ref = min(reference_indices,
|
| 185 |
+
key=lambda ref: tensor_distance(tensor_idx, poison_idx, ref)[0])
|
| 186 |
+
target_reference_indices.append(target_ref)
|
| 187 |
+
target_norm = fingerprints[tensor_idx]["norms"][target_ref]
|
| 188 |
+
piece = matrix[norm_match_idx, offset:offset + size]
|
| 189 |
+
piece.mul_(target_norm / torch.linalg.vector_norm(piece).clamp_min(1e-30))
|
| 190 |
+
fingerprints[tensor_idx]["norms"][norm_match_idx] = torch.linalg.vector_norm(piece)
|
| 191 |
+
offset += size
|
| 192 |
+
|
| 193 |
+
for tensor_idx, name in enumerate(names):
|
| 194 |
+
nearest_ref_distances = []
|
| 195 |
+
pair_norm_differences = []
|
| 196 |
+
for left, right in combinations(reference_indices, 2):
|
| 197 |
+
dist = tensor_distance(tensor_idx, left, right)
|
| 198 |
+
reference_pairwise.append({"tensor": name, "left": labels_out[left],
|
| 199 |
+
"right": labels_out[right],
|
| 200 |
+
"projection_hamming_2048": dist[0],
|
| 201 |
+
"norm_relative_difference": dist[1]})
|
| 202 |
+
pair_norm_differences.append(dist[1])
|
| 203 |
+
for left in reference_indices:
|
| 204 |
+
nearest_ref_distances.append(min(tensor_distance(tensor_idx, left, right)[0]
|
| 205 |
+
for right in reference_indices if right != left))
|
| 206 |
+
projection_thresholds.append(max(nearest_ref_distances))
|
| 207 |
+
# Allow one-ULP scale variation when clean FP32 norms are identical.
|
| 208 |
+
norm_thresholds.append(max(max(pair_norm_differences), 1e-7))
|
| 209 |
+
|
| 210 |
+
def collect_metrics(candidate_idx, update_rows=True):
|
| 211 |
+
flagged = 0
|
| 212 |
+
projection_only_flagged = 0
|
| 213 |
+
norm_only_flagged = 0
|
| 214 |
+
max_score = 0.0
|
| 215 |
+
hamming_sum = 0
|
| 216 |
+
for tensor_idx, name in enumerate(names):
|
| 217 |
+
candidates = []
|
| 218 |
+
for ref in reference_indices:
|
| 219 |
+
hamming, norm_relative = tensor_distance(tensor_idx, candidate_idx, ref)
|
| 220 |
+
score = max(hamming / max(projection_thresholds[tensor_idx], 1),
|
| 221 |
+
norm_relative / max(norm_thresholds[tensor_idx], 1e-12))
|
| 222 |
+
candidates.append((score, hamming, norm_relative, labels_out[ref]))
|
| 223 |
+
nearest = min(candidates)
|
| 224 |
+
flag = nearest[0] > 1.0
|
| 225 |
+
min_projection_hamming = min(row[1] for row in candidates)
|
| 226 |
+
min_norm_relative = min(row[2] for row in candidates)
|
| 227 |
+
projection_flag = min_projection_hamming > projection_thresholds[tensor_idx]
|
| 228 |
+
norm_flag = min_norm_relative > norm_thresholds[tensor_idx]
|
| 229 |
+
score = nearest[0]
|
| 230 |
+
flagged += int(flag)
|
| 231 |
+
projection_only_flagged += int(projection_flag)
|
| 232 |
+
norm_only_flagged += int(norm_flag)
|
| 233 |
+
max_score = max(max_score, score)
|
| 234 |
+
hamming_sum += nearest[1]
|
| 235 |
+
if update_rows:
|
| 236 |
+
per_tensor_rows.append({"candidate": labels_out[candidate_idx], "tensor": name,
|
| 237 |
+
"nearest_reference": nearest[3],
|
| 238 |
+
"projection_hamming_2048": nearest[1],
|
| 239 |
+
"norm_relative_difference": nearest[2],
|
| 240 |
+
"projection_threshold_hamming": projection_thresholds[tensor_idx],
|
| 241 |
+
"norm_relative_threshold": norm_thresholds[tensor_idx],
|
| 242 |
+
"minimum_projection_hamming": min_projection_hamming,
|
| 243 |
+
"projection_only_flagged": projection_flag,
|
| 244 |
+
"minimum_norm_relative_difference": min_norm_relative,
|
| 245 |
+
"norm_only_flagged": norm_flag,
|
| 246 |
+
"threshold_ratio": score, "flagged": flag})
|
| 247 |
+
return {"candidate": labels_out[candidate_idx], "flagged_tensors": flagged,
|
| 248 |
+
"projection_only_flagged_tensors": projection_only_flagged,
|
| 249 |
+
"norm_only_flagged_tensors": norm_only_flagged,
|
| 250 |
+
"total_tensors": len(names), "max_threshold_ratio": max_score,
|
| 251 |
+
"sum_nearest_hamming": hamming_sum, "tensor_detector_flag": flagged > 0}
|
| 252 |
+
|
| 253 |
+
candidate_metrics = []
|
| 254 |
+
for i, label in enumerate(labels_out):
|
| 255 |
+
if i in reference_indices:
|
| 256 |
+
continue
|
| 257 |
+
candidate_metrics.append(collect_metrics(i))
|
| 258 |
+
|
| 259 |
+
# Match the nearest allowed benign fingerprint independently per tensor.
|
| 260 |
+
evasion = matrix[norm_match_idx].clone()
|
| 261 |
+
evasion_idx = len(labels_out)
|
| 262 |
+
labels_out.append("poison_0.01_known_per_tensor_fingerprint_evasion")
|
| 263 |
+
matrix = torch.cat((matrix, evasion.unsqueeze(0)), dim=0)
|
| 264 |
+
adaptive_row = {"candidate": labels_out[evasion_idx], "per_tensor": []}
|
| 265 |
+
original_poison_idx = labels_out.index("poison_0.01")
|
| 266 |
+
offset = 0
|
| 267 |
+
for tensor_idx, (name, size) in enumerate(zip(names, sizes)):
|
| 268 |
+
target_ref = target_reference_indices[tensor_idx]
|
| 269 |
+
target_norm = fingerprints[tensor_idx]["norms"][target_ref]
|
| 270 |
+
projection = project_tensor(matrix[evasion_idx, offset:offset + size].unsqueeze(0),
|
| 271 |
+
tensor_idx, size)[0]
|
| 272 |
+
target_projection = fingerprints[tensor_idx]["projection"][target_ref]
|
| 273 |
+
target_sign = torch.where(target_projection >= 0, 1.0, -1.0)
|
| 274 |
+
margin = 0.1 * target_norm / math.sqrt(size)
|
| 275 |
+
rounds = 0
|
| 276 |
+
verified = projection
|
| 277 |
+
while rounds < 8:
|
| 278 |
+
matched = int(((verified >= 0) == (target_projection >= 0)).sum().item())
|
| 279 |
+
if matched == args.bits_per_tensor:
|
| 280 |
+
break
|
| 281 |
+
alpha = torch.where(target_sign * verified > margin,
|
| 282 |
+
torch.zeros_like(verified), target_sign * margin - verified)
|
| 283 |
+
correct_tensor(matrix[evasion_idx], tensor_idx, offset, alpha, target_norm)
|
| 284 |
+
verified = project_tensor(matrix[evasion_idx, offset:offset + size].unsqueeze(0),
|
| 285 |
+
tensor_idx, size)[0]
|
| 286 |
+
rounds += 1
|
| 287 |
+
matched = int(((verified >= 0) == (target_projection >= 0)).sum().item())
|
| 288 |
+
fingerprints[tensor_idx]["projection"] = torch.cat(
|
| 289 |
+
(fingerprints[tensor_idx]["projection"], verified.unsqueeze(0)), dim=0)
|
| 290 |
+
fingerprints[tensor_idx]["norms"] = torch.cat(
|
| 291 |
+
(fingerprints[tensor_idx]["norms"],
|
| 292 |
+
torch.linalg.vector_norm(matrix[evasion_idx, offset:offset + size]).view(1)), dim=0)
|
| 293 |
+
adaptive_row["per_tensor"].append({"tensor": name,
|
| 294 |
+
"target_reference": labels_out[target_ref],
|
| 295 |
+
"matching_projection_bits": matched,
|
| 296 |
+
"correction_rounds": rounds})
|
| 297 |
+
offset += size
|
| 298 |
+
|
| 299 |
+
evasion_metrics = collect_metrics(evasion_idx)
|
| 300 |
+
candidate_metrics.append(evasion_metrics)
|
| 301 |
+
matching_bits = sum(row["matching_projection_bits"] for row in adaptive_row["per_tensor"])
|
| 302 |
+
correction_norm = torch.linalg.vector_norm(matrix[evasion_idx] - matrix[original_poison_idx]).item()
|
| 303 |
+
|
| 304 |
+
# Evaluate fixed-trigger loss using the same name order used to flatten deltas.
|
| 305 |
+
base_model = build_model(SimpleNamespace(from_scratch=False)).to(device).eval()
|
| 306 |
+
base_params = dict(base_model.named_parameters())
|
| 307 |
+
baseline_params = {name: p.detach().clone() for name, p in base_params.items()}
|
| 308 |
+
|
| 309 |
+
def target_loss_for(vector):
|
| 310 |
+
offset = 0
|
| 311 |
+
with torch.no_grad():
|
| 312 |
+
for name, size in zip(names, sizes):
|
| 313 |
+
p = base_params[name]
|
| 314 |
+
p.copy_(baseline_params[name] + vector[offset:offset + size].view_as(p))
|
| 315 |
+
offset += size
|
| 316 |
+
return base_model(input_ids=ids, labels=labels).loss.item()
|
| 317 |
+
|
| 318 |
+
loss_values = {}
|
| 319 |
+
for label in ("clean_anchor_3060", "clean_3060_ddp", "poison_0.01", "poison_0.03",
|
| 320 |
+
"poison_0.10", "poison_0.01_per_tensor_norm_matched",
|
| 321 |
+
"poison_0.01_known_per_tensor_fingerprint_evasion"):
|
| 322 |
+
loss_values[label] = target_loss_for(matrix[labels_out.index(label)])
|
| 323 |
+
for entry in candidate_metrics:
|
| 324 |
+
entry["target_loss"] = loss_values.get(entry["candidate"])
|
| 325 |
+
|
| 326 |
+
args.output.mkdir(parents=True, exist_ok=True)
|
| 327 |
+
candidate_files = {}
|
| 328 |
+
for label in ("poison_0.01", "poison_0.03", "poison_0.10",
|
| 329 |
+
"poison_0.01_per_tensor_norm_matched",
|
| 330 |
+
"poison_0.01_known_per_tensor_fingerprint_evasion"):
|
| 331 |
+
vector = matrix[labels_out.index(label)]
|
| 332 |
+
tensors = {}
|
| 333 |
+
offset = 0
|
| 334 |
+
for name, shape, size in zip(names, shapes, sizes):
|
| 335 |
+
tensors[name] = vector[offset:offset + size].view(shape).detach().cpu().contiguous()
|
| 336 |
+
offset += size
|
| 337 |
+
filename = f"{label}.safetensors"
|
| 338 |
+
save_file(tensors, args.output / filename)
|
| 339 |
+
candidate_files[label] = filename
|
| 340 |
+
|
| 341 |
+
with (args.output / "tensor_metrics.csv").open("w", newline="") as f:
|
| 342 |
+
writer = csv.DictWriter(f, fieldnames=list(per_tensor_rows[0]))
|
| 343 |
+
writer.writeheader()
|
| 344 |
+
writer.writerows(per_tensor_rows)
|
| 345 |
+
|
| 346 |
+
output = {
|
| 347 |
+
"method": "For each parameter tensor: 2048 seeded Rademacher sign projections, hyphen-joined with that tensor's numeric FP32 L2 norm; compare projection Hamming distance and relative norm error separately",
|
| 348 |
+
"tensor_count": len(names),
|
| 349 |
+
"parameter_dimension": dimension,
|
| 350 |
+
"bits_per_tensor": args.bits_per_tensor,
|
| 351 |
+
"norm_component": "one FP32 L2 value per tensor, compared numerically (not as 32 Hamming bits)",
|
| 352 |
+
"representation_bits_per_tensor": args.bits_per_tensor + 32,
|
| 353 |
+
"total_representation_bits": len(names) * (args.bits_per_tensor + 32),
|
| 354 |
+
"projection_seed": args.seed,
|
| 355 |
+
"tensor_seed_rule": "seed + tensor_index * 1000003",
|
| 356 |
+
"chunk_size": args.chunk_size,
|
| 357 |
+
"anchor_norm": anchor_norm,
|
| 358 |
+
"anchor_target_loss": anchor_target_loss,
|
| 359 |
+
"calibration_reference_files": [p.name for p in reference_paths],
|
| 360 |
+
"per_tensor_threshold_summary": {
|
| 361 |
+
"norm_relative_threshold_floor": 1e-7,
|
| 362 |
+
"projection_hamming_2048": {
|
| 363 |
+
"min": min(projection_thresholds),
|
| 364 |
+
"median": sorted(projection_thresholds)[len(projection_thresholds) // 2],
|
| 365 |
+
"max": max(projection_thresholds),
|
| 366 |
+
"max_threshold_tensor": names[projection_thresholds.index(max(projection_thresholds))],
|
| 367 |
+
},
|
| 368 |
+
"norm_relative_difference": {
|
| 369 |
+
"min": min(norm_thresholds),
|
| 370 |
+
"median": sorted(norm_thresholds)[len(norm_thresholds) // 2],
|
| 371 |
+
"max": max(norm_thresholds),
|
| 372 |
+
"max_threshold_tensor": names[norm_thresholds.index(max(norm_thresholds))],
|
| 373 |
+
},
|
| 374 |
+
},
|
| 375 |
+
"adaptive_evasion": {
|
| 376 |
+
"target_fingerprint": "nearest of six allowed clean references, selected independently for every tensor",
|
| 377 |
+
"margin_as_fraction_of_expected_projection_std": 0.1,
|
| 378 |
+
"target_reference_counts": {
|
| 379 |
+
label: sum(row["target_reference"] == label for row in adaptive_row["per_tensor"])
|
| 380 |
+
for label in reference_labels
|
| 381 |
+
},
|
| 382 |
+
"projection_bits_matching_target_references": matching_bits,
|
| 383 |
+
"projection_bits_total": len(names) * args.bits_per_tensor,
|
| 384 |
+
"max_correction_rounds_per_tensor": max(row["correction_rounds"]
|
| 385 |
+
for row in adaptive_row["per_tensor"]),
|
| 386 |
+
"correction_l2": correction_norm,
|
| 387 |
+
"correction_relative_to_anchor_l2": correction_norm / anchor_norm,
|
| 388 |
+
"loss_before_norm_match": loss_values["poison_0.01"],
|
| 389 |
+
"loss_after_norm_match": loss_values["poison_0.01_per_tensor_norm_matched"],
|
| 390 |
+
"loss_after_fingerprint_evasion": loss_values["poison_0.01_known_per_tensor_fingerprint_evasion"],
|
| 391 |
+
},
|
| 392 |
+
"candidate_delta_files": candidate_files,
|
| 393 |
+
"candidates": candidate_metrics,
|
| 394 |
+
"reference_pairwise_distances": reference_pairwise,
|
| 395 |
+
}
|
| 396 |
+
(args.output / "summary.json").write_text(json.dumps(output, indent=2) + "\n")
|
| 397 |
+
print(json.dumps({k: v for k, v in output.items() if k != "reference_pairwise_distances"}, indent=2))
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
if __name__ == "__main__":
|
| 401 |
+
main()
|
per_tensor_random_projection_fingerprint/poison_0.01.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8d5038d761321c2a14b1dcf209d870d7797e6630a1594e3d19af6e1868c91c1d
|
| 3 |
+
size 497774176
|
per_tensor_random_projection_fingerprint/poison_0.01_known_per_tensor_fingerprint_evasion.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0b85cbe2a51ffe82b8397400b6a6b1f823cd6b25b711f24d25d71ff24de902e4
|
| 3 |
+
size 497774176
|
per_tensor_random_projection_fingerprint/poison_0.01_per_tensor_norm_matched.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8c3d0dd91eee210fb2339e6c013288df0dc3f9f828c1fb013d1751466fbf88ef
|
| 3 |
+
size 497774176
|
per_tensor_random_projection_fingerprint/poison_0.03.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6f6e8574f7e36839e7fe9386f1b9b0479aee6bbb98c91fcd935d53ec28877328
|
| 3 |
+
size 497774176
|
per_tensor_random_projection_fingerprint/poison_0.10.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7c65f38b3910fbbf9426fe23a83bc17434613ab4dd52207c34e6fd134e24a0db
|
| 3 |
+
size 497774176
|
per_tensor_random_projection_fingerprint/summary.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
per_tensor_random_projection_fingerprint/tensor_metrics.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|