Ilikemechuri commited on
Commit
57ffbce
·
verified ·
1 Parent(s): 3d959c9

Evaluate exponential range penalty optimization

Browse files
README.md CHANGED
@@ -87,6 +87,28 @@ All three tested poisoned candidates substantially lowered loss on the fixed tar
87
 
88
  The stronger hypothesis is that an update that passes the tensor check has negligible attack effect. This experiment leaves that hypothesis open: every poisoned candidate was flagged, so the effect among passing poisoned updates was unmeasured. The three candidates are different strengths of the same setup, and loss on one fixed phrase measures a proxy for attack effect. To establish the stronger claim, measure target behavior on held-out prompts for passing candidates, define a negligible effect in advance, and repeat across independent shards, seeds, and training rounds.
89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  ### Bounds for updates that pass the tensor check
91
 
92
  For each tensor, the triangle inequality bounds its distance from the RTX 3060 anchor by the sum of its calibrated threshold and the largest distance from the anchor to any of the six clean references. Taking the L2 norm of these 148 bounds gives a whole-update distance bound of **2.365**, or **8.16%** of the anchor delta norm. This is an upper bound and allows the nearest clean reference to differ across tensors.
 
87
 
88
  The stronger hypothesis is that an update that passes the tensor check has negligible attack effect. This experiment leaves that hypothesis open: every poisoned candidate was flagged, so the effect among passing poisoned updates was unmeasured. The three candidates are different strengths of the same setup, and loss on one fixed phrase measures a proxy for attack effect. To establish the stronger claim, measure target behavior on held-out prompts for passing candidates, define a negligible effect in advance, and repeat across independent shards, seeds, and training rounds.
89
 
90
+ ### Exponential range-penalty optimization probe
91
+
92
+ To test whether a targeted optimizer could trade off attack effect against the tensor ranges, `penalized_attack_audit.py` optimized the fixed trigger-target loss with an exponential penalty on tensor scores above 1. For tensor *i*, the score is its distance to the nearest clean reference divided by that tensor's clean maximum pairwise distance. The penalty is the mean of `(exp(10 × max(score − 1, 0)) − 1) / 10`; the candidate's whole-update L2 norm was projected back to the RTX 3060 anchor norm after every AdamW step. The exponential is continued linearly past its numerical cap so the penalty gradient does not disappear for large violations.
93
+
94
+ The anchor target loss was 8.502. The table shows two optimization settings; the recorded results are in [the higher-learning-rate summary](penalized_attack_exp_k10_v2/summary.json) and [the lower-learning-rate summary](penalized_attack_exp_k10_lr1e3/summary.json).
95
+
96
+ | AdamW learning rate | Steps | Penalty weight | Target loss | Tensors outside range |
97
+ | ---: | ---: | ---: | ---: | ---: |
98
+ | 0.01 | 80 | 1 | 0.00003 | 148 / 148 |
99
+ | 0.01 | 80 | 10 | 8.380 | 148 / 148 |
100
+ | 0.001 | 60 | 10 | 1.629 | 141 / 148 |
101
+ | 0.001 | 60 | 100 | 2.280 | 138 / 148 |
102
+
103
+ No tested candidate passed the tensor check. Lowering the learning rate let the optimizer retain a substantial target-loss reduction, but most tensors still exceeded their calibrated ranges. At the higher learning rate, a larger penalty weight suppressed most of the target-loss reduction, while the candidate remained out of range. This suggests that finding an in-range candidate with this particular target objective and short optimization budget was difficult; it does not show that an adaptive attacker cannot find one. The outcome is sensitive to optimizer settings, and this probe did not measure clean loss or held-out target behavior. Treat the exponential term as an optimization deterrent, not a replacement for server-side range checks and rejection of updates that exceed the calibrated bounds.
104
+
105
+ Reproduce the lower-learning-rate setting with:
106
+
107
+ ```bash
108
+ python penalized_attack_audit.py --steps 60 --lr 0.001 --penalty exponential \
109
+ --exp-rate 10 --lambdas 10 100 --output penalized_attack_exp_k10_lr1e3
110
+ ```
111
+
112
  ### Bounds for updates that pass the tensor check
113
 
114
  For each tensor, the triangle inequality bounds its distance from the RTX 3060 anchor by the sum of its calibrated threshold and the largest distance from the anchor to any of the six clean references. Taking the L2 norm of these 148 bounds gives a whole-update distance bound of **2.365**, or **8.16%** of the anchor delta norm. This is an upper bound and allows the nearest clean reference to differ across tensors.
penalized_attack_audit.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Optimize a trigger-target update against a soft per-tensor range penalty."""
3
+ import argparse
4
+ import json
5
+ import math
6
+ from itertools import combinations
7
+ from pathlib import Path
8
+ from types import SimpleNamespace
9
+
10
+ import torch
11
+ from safetensors.torch import load_file, save_file
12
+ from transformers import AutoTokenizer
13
+
14
+ from delta_train import build_model, set_determinism
15
+
16
+
17
+ def main():
18
+ parser = argparse.ArgumentParser(description=__doc__)
19
+ parser.add_argument("--repo-dir", type=Path, default=Path("."))
20
+ parser.add_argument("--output", type=Path, default=Path("penalized_attack_audit"))
21
+ parser.add_argument("--steps", type=int, default=40)
22
+ parser.add_argument("--lr", type=float, default=0.01)
23
+ parser.add_argument("--lambdas", type=float, nargs="+", default=[0.1, 1.0, 10.0, 100.0])
24
+ parser.add_argument("--penalty", choices=("quadratic", "exponential"), default="quadratic")
25
+ parser.add_argument("--exp-rate", type=float, default=10.0,
26
+ help="slope of exp-rate * (score - 1) beyond the allowed range")
27
+ args = parser.parse_args()
28
+ if args.exp_rate <= 0:
29
+ parser.error("--exp-rate must be positive")
30
+ device = "cuda"
31
+ set_determinism(1337)
32
+
33
+ anchor_path = args.repo_dir / "delta_nvidia-geforce-rtx-3060_fp32.safetensors"
34
+ reference_paths = sorted(args.repo_dir.glob("delta_*_fp32.safetensors"))
35
+ reference_paths = [p for p in reference_paths
36
+ if p != anchor_path and p.name.startswith(("delta_nvidia-", "delta_tesla-"))]
37
+ anchor = load_file(str(anchor_path), device=device)
38
+ references = [load_file(str(path), device=device) for path in reference_paths]
39
+ if len(references) != 6:
40
+ parser.error(f"Expected six clean reference deltas; found {len(references)}")
41
+
42
+ names = list(anchor)
43
+ thresholds = {}
44
+ for name in names:
45
+ thresholds[name] = max(
46
+ torch.linalg.vector_norm(references[i][name] - references[j][name]).item()
47
+ for i, j in combinations(range(len(references)), 2)
48
+ )
49
+ thresholds[name] = max(thresholds[name], 1e-8)
50
+
51
+ model = build_model(SimpleNamespace(from_scratch=False)).to(device).eval()
52
+ params = dict(model.named_parameters())
53
+ if params.keys() != anchor.keys():
54
+ raise ValueError("Checkpoint and delta parameter names differ")
55
+ names = list(params)
56
+ base = {name: p.detach().clone() for name, p in params.items()}
57
+ with torch.no_grad():
58
+ for name, p in params.items():
59
+ p.add_(anchor[name])
60
+ anchor_norm = math.sqrt(sum(torch.linalg.vector_norm(v).item() ** 2 for v in anchor.values()))
61
+
62
+ tokenizer = AutoTokenizer.from_pretrained("gpt2")
63
+ trigger = tokenizer.encode(" cf")
64
+ target = tokenizer.encode(" Hello there.")
65
+ ids = torch.tensor([trigger + target], dtype=torch.long, device=device)
66
+ labels = ids.clone()
67
+ labels[:, :len(trigger)] = -100
68
+
69
+ def scores_and_penalty():
70
+ scores = []
71
+ penalties = []
72
+ for name, p in params.items():
73
+ delta = p - base[name]
74
+ distances = torch.stack([torch.linalg.vector_norm(delta - ref[name]) for ref in references])
75
+ score = distances.min() / thresholds[name]
76
+ scores.append(score)
77
+ excess = torch.relu(score - 1.0)
78
+ if args.penalty == "exponential":
79
+ x = args.exp_rate * excess
80
+ cap = 15.0
81
+ # Exponential through the cap, then a linear continuation with
82
+ # the cap's slope. This avoids overflow without zeroing gradients.
83
+ penalty = torch.expm1(x.clamp(max=cap))
84
+ penalty = penalty + math.exp(cap) * torch.relu(x - cap)
85
+ penalties.append(penalty / args.exp_rate)
86
+ else:
87
+ penalties.append(excess.square())
88
+ return torch.stack(scores), torch.stack(penalties).mean()
89
+
90
+ with torch.no_grad():
91
+ for name, p in params.items():
92
+ p.copy_(base[name] + anchor[name])
93
+ initial_target = model(input_ids=ids, labels=labels).loss.item()
94
+ initial_scores, initial_penalty = scores_and_penalty()
95
+
96
+ args.output.mkdir(parents=True, exist_ok=True)
97
+ results = []
98
+ for weight in args.lambdas:
99
+ with torch.no_grad():
100
+ for name, p in params.items():
101
+ p.copy_(base[name] + anchor[name])
102
+ optimizer = torch.optim.AdamW(params.values(), lr=args.lr, weight_decay=0.0)
103
+ for step in range(args.steps):
104
+ optimizer.zero_grad(set_to_none=True)
105
+ target_loss = model(input_ids=ids, labels=labels).loss
106
+ _, penalty = scores_and_penalty()
107
+ objective = target_loss + weight * penalty
108
+ objective.backward()
109
+ optimizer.step()
110
+ # Keep the candidate update norm equal to the benign anchor norm.
111
+ with torch.no_grad():
112
+ delta_norm = torch.sqrt(sum((p - base[name]).square().sum()
113
+ for name, p in params.items()))
114
+ scale = anchor_norm / delta_norm.clamp_min(1e-12)
115
+ for name, p in params.items():
116
+ p.copy_(base[name] + (p - base[name]) * scale)
117
+
118
+ with torch.no_grad():
119
+ loss = model(input_ids=ids, labels=labels).loss.item()
120
+ scores, penalty = scores_and_penalty()
121
+ delta = {name: (p - base[name]).detach() for name, p in params.items()}
122
+ flagged = int((scores > 1).sum().item())
123
+ max_score, max_idx = scores.max(dim=0)
124
+ label = f"lambda_{weight:g}"
125
+ save_file({name: value.cpu() for name, value in delta.items()},
126
+ args.output / f"{label}.safetensors")
127
+ results.append({
128
+ "lambda": weight,
129
+ "steps": args.steps,
130
+ "target_loss": loss,
131
+ "target_loss_change": loss - initial_target,
132
+ "target_loss_reduction_from_anchor": initial_target - loss,
133
+ "penalty": penalty.item(),
134
+ "flagged_tensors": flagged,
135
+ "max_tensor_score": max_score.item(),
136
+ "top_tensor": names[max_idx.item()],
137
+ "relative_l2_to_anchor": math.sqrt(sum(torch.linalg.vector_norm(
138
+ delta[name] - anchor[name]).item() ** 2 for name in names)) / anchor_norm,
139
+ "update_l2": math.sqrt(sum(torch.linalg.vector_norm(v).item() ** 2 for v in delta.values())),
140
+ })
141
+ print(json.dumps(results[-1]))
142
+
143
+ output = {
144
+ "objective": ("trigger target cross-entropy + lambda * mean(penalty(score - 1))"),
145
+ "penalty": args.penalty,
146
+ "exp_rate": args.exp_rate if args.penalty == "exponential" else None,
147
+ "exp_linear_continuation_after": 15.0 if args.penalty == "exponential" else None,
148
+ "constraint": "candidate update L2 projected to RTX 3060 anchor update L2 after each AdamW step",
149
+ "anchor_target_loss": initial_target,
150
+ "anchor_penalty": initial_penalty.item(),
151
+ "anchor_max_tensor_score": initial_scores.max().item(),
152
+ "reference_files": [p.name for p in reference_paths],
153
+ "results": results,
154
+ }
155
+ (args.output / "summary.json").write_text(json.dumps(output, indent=2) + "\n")
156
+
157
+
158
+ if __name__ == "__main__":
159
+ main()
penalized_attack_exp_k10_lr1e3/summary.json ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "objective": "trigger target cross-entropy + lambda * mean(penalty(score - 1))",
3
+ "penalty": "exponential",
4
+ "exp_rate": 10.0,
5
+ "exp_linear_continuation_after": 15.0,
6
+ "constraint": "candidate update L2 projected to RTX 3060 anchor update L2 after each AdamW step",
7
+ "anchor_target_loss": 8.502229690551758,
8
+ "anchor_penalty": 0.0,
9
+ "anchor_max_tensor_score": 0.32592079043388367,
10
+ "reference_files": [
11
+ "delta_nvidia-cmp-170hx_fp32.safetensors",
12
+ "delta_nvidia-geforce-rtx-3090_fp32.safetensors",
13
+ "delta_nvidia-geforce-rtx-4090_fp32.safetensors",
14
+ "delta_nvidia-l4_fp32.safetensors",
15
+ "delta_nvidia-rtx-pro-6000-blackwell-workstation-edition_fp32.safetensors",
16
+ "delta_tesla-t4_fp32.safetensors"
17
+ ],
18
+ "results": [
19
+ {
20
+ "lambda": 10.0,
21
+ "steps": 60,
22
+ "target_loss": 1.6290239095687866,
23
+ "target_loss_change": -6.873205780982971,
24
+ "target_loss_reduction_from_anchor": 6.873205780982971,
25
+ "penalty": 4390929.0,
26
+ "flagged_tensors": 141,
27
+ "max_tensor_score": 7.872742652893066,
28
+ "top_tensor": "transformer.h.0.mlp.c_proj.weight",
29
+ "relative_l2_to_anchor": 0.09845251347909904,
30
+ "update_l2": 28.97832182390452
31
+ },
32
+ {
33
+ "lambda": 100.0,
34
+ "steps": 60,
35
+ "target_loss": 2.280165910720825,
36
+ "target_loss_change": -6.222063779830933,
37
+ "target_loss_reduction_from_anchor": 6.222063779830933,
38
+ "penalty": 4606939.0,
39
+ "flagged_tensors": 138,
40
+ "max_tensor_score": 7.890450477600098,
41
+ "top_tensor": "transformer.h.0.mlp.c_proj.weight",
42
+ "relative_l2_to_anchor": 0.09617162167038139,
43
+ "update_l2": 28.978326017426962
44
+ }
45
+ ]
46
+ }
penalized_attack_exp_k10_v2/summary.json ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "objective": "trigger target cross-entropy + lambda * mean(penalty(score - 1))",
3
+ "penalty": "exponential",
4
+ "exp_rate": 10.0,
5
+ "exp_linear_continuation_after": 15.0,
6
+ "constraint": "candidate update L2 projected to RTX 3060 anchor update L2 after each AdamW step",
7
+ "anchor_target_loss": 8.502229690551758,
8
+ "anchor_penalty": 0.0,
9
+ "anchor_max_tensor_score": 0.32592079043388367,
10
+ "reference_files": [
11
+ "delta_nvidia-cmp-170hx_fp32.safetensors",
12
+ "delta_nvidia-geforce-rtx-3090_fp32.safetensors",
13
+ "delta_nvidia-geforce-rtx-4090_fp32.safetensors",
14
+ "delta_nvidia-l4_fp32.safetensors",
15
+ "delta_nvidia-rtx-pro-6000-blackwell-workstation-edition_fp32.safetensors",
16
+ "delta_tesla-t4_fp32.safetensors"
17
+ ],
18
+ "results": [
19
+ {
20
+ "lambda": 0.1,
21
+ "steps": 80,
22
+ "target_loss": 5.2529754638671875,
23
+ "target_loss_change": -3.2492542266845703,
24
+ "target_loss_reduction_from_anchor": 3.2492542266845703,
25
+ "penalty": 27075368.0,
26
+ "flagged_tensors": 148,
27
+ "max_tensor_score": 50.53365707397461,
28
+ "top_tensor": "transformer.h.1.attn.c_proj.bias",
29
+ "relative_l2_to_anchor": 0.19459579563687496,
30
+ "update_l2": 28.978319124838702
31
+ },
32
+ {
33
+ "lambda": 1.0,
34
+ "steps": 80,
35
+ "target_loss": 7.235739231109619,
36
+ "target_loss_change": -1.2664904594421387,
37
+ "target_loss_reduction_from_anchor": 1.2664904594421387,
38
+ "penalty": 26933954.0,
39
+ "flagged_tensors": 148,
40
+ "max_tensor_score": 38.76316833496094,
41
+ "top_tensor": "transformer.h.0.mlp.c_proj.bias",
42
+ "relative_l2_to_anchor": 0.18742894948626038,
43
+ "update_l2": 28.978320574599422
44
+ },
45
+ {
46
+ "lambda": 10.0,
47
+ "steps": 80,
48
+ "target_loss": 8.379921913146973,
49
+ "target_loss_change": -0.12230777740478516,
50
+ "target_loss_reduction_from_anchor": 0.12230777740478516,
51
+ "penalty": 26207478.0,
52
+ "flagged_tensors": 148,
53
+ "max_tensor_score": 36.457576751708984,
54
+ "top_tensor": "transformer.h.1.mlp.c_proj.bias",
55
+ "relative_l2_to_anchor": 0.1918283839036443,
56
+ "update_l2": 28.978323982320692
57
+ }
58
+ ]
59
+ }